Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1614_GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment/3.3/SolutionCreators/GreedyRandomizedSolutionCreator.cs

Last change on this file was 16728, checked in by abeham, 6 years ago

#1614: updated to new persistence and .NET 4.6.1

File size: 10.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Threading;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.IntegerVectorEncoding;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Random;
33using HEAL.Attic;
34
35namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment {
36  /// <summary>
37  /// This is an implementation of the algorithm described in Mateus, G.R., Resende, M.G.C. & Silva, R.M.A. J Heuristics (2011) 17: 527. https://doi.org/10.1007/s10732-010-9144-0
38  /// </summary>
39  [Item("GreedyRandomizedSolutionCreator", "Creates a solution according to the procedure described in Mateus, G., Resende, M., and Silva, R. 2011. GRASP with path-relinking for the generalized quadratic assignment problem. Journal of Heuristics 17, Springer Netherlands, pp. 527-565.")]
40  [StorableType("44919EFC-AF47-4F0D-8EE4-F5AECBF776CA")]
41  public class GreedyRandomizedSolutionCreator : GQAPStochasticSolutionCreator {
42
43    public IValueLookupParameter<IntValue> MaximumTriesParameter {
44      get { return (IValueLookupParameter<IntValue>)Parameters["MaximumTries"]; }
45    }
46    public IValueLookupParameter<BoolValue> CreateMostFeasibleSolutionParameter {
47      get { return (IValueLookupParameter<BoolValue>)Parameters["CreateMostFeasibleSolution"]; }
48    }
49
50    [StorableConstructor]
51    protected GreedyRandomizedSolutionCreator(StorableConstructorFlag _) : base(_) { }
52    protected GreedyRandomizedSolutionCreator(GreedyRandomizedSolutionCreator original, Cloner cloner)
53      : base(original, cloner) { }
54    public GreedyRandomizedSolutionCreator()
55      : base() {
56      Parameters.Add(new ValueLookupParameter<IntValue>("MaximumTries", "The maximum number of tries to create a feasible solution after which an exception is thrown. If it is set to 0 or a negative value there will be an infinite number of attempts.", new IntValue(100000)));
57      Parameters.Add(new ValueLookupParameter<BoolValue>("CreateMostFeasibleSolution", "If this is set to true the operator will always succeed, and outputs the solution with the least violation instead of throwing an exception.", new BoolValue(false)));
58    }
59
60    public override IDeepCloneable Clone(Cloner cloner) {
61      return new GreedyRandomizedSolutionCreator(this, cloner);
62    }
63
64    public static IntegerVector CreateSolution(IRandom random, GQAPInstance problemInstance,
65      int maximumTries, bool createMostFeasibleSolution, CancellationToken cancelToken) {
66      var weights = problemInstance.Weights;
67      var distances = problemInstance.Distances;
68      var installCosts = problemInstance.InstallationCosts;
69      var demands = problemInstance.Demands;
70      var capacities = problemInstance.Capacities.ToArray();
71      var transportCosts = problemInstance.TransportationCosts;
72      var equipments = demands.Length;
73      var locations = capacities.Length;
74      int tries = 0;
75      var slack = new double[locations];
76      double minViolation = double.MaxValue;
77      int[] assignment = null;
78      int[] bestAssignment = null;
79      var F = new List<int>(equipments); // set of (initially) all facilities / equipments
80      var CF = new List<int>(equipments); // set of chosen facilities / equipments
81      var L = new List<int>(locations); // set of (initially) all locations
82      var CL_list = new List<int>(locations); // list of chosen locations
83      var CL_selected = new bool[locations]; // bool decision if location is chosen
84      var T = new List<int>(equipments); // set of facilities / equpiments that can be assigned to the set of chosen locations (CL)
85      var H = new double[locations]; // proportions for choosing locations in stage 1
86      var W = new double[equipments]; // proportions for choosing facilities in stage 2
87      var Z = new double[locations]; // proportions for choosing locations in stage 2
88     
89      for (var k = 0; k < equipments; k++) {
90        for (var h = 0; h < equipments; h++) {
91          if (k == h) continue;
92          W[k] += weights[k, h];
93        }
94        W[k] *= demands[k];
95      }
96
97      while (maximumTries <= 0 || tries < maximumTries) {
98        cancelToken.ThrowIfCancellationRequested();
99
100        assignment = new int[equipments];
101
102        Array.Copy(capacities, slack, locations); // line 2 of Algorihm 2
103        CF.Clear(); // line 2 of Algorihm 2
104        Array.Clear(CL_selected, 0, locations); // line 2 of Algorihm 2
105        CL_list.Clear(); // line 2 of Algorihm 2
106        T.Clear(); // line 2 of Algorihm 2
107
108        F.Clear(); F.AddRange(Enumerable.Range(0, equipments)); // line 2 of Algorihm 2
109        L.Clear(); L.AddRange(Enumerable.Range(0, locations)); // line 2 of Algorihm 2
110
111        Array.Clear(H, 0, H.Length);
112
113        double threshold = 1.0; // line 3 of Algorithm 2
114        do { // line 4 of Algorithm 2
115          if (L.Count > 0 && random.NextDouble() < threshold) { // line 5 of Algorithm 2
116            // H is the proportion that a location is chosen
117            // The paper doesn't mention what happens if the candidate list CL
118            // does not contain an element in which case according to the formula
119            // all H_k elements would be 0 which would be equal to random selection
120            var HH = L.Select(x => H[x]);
121            int l = L.SampleProportional(random, 1, HH, false, false).Single(); // line 6 of Algorithm 2
122            L.Remove(l); // line 7 of Algorithm 2
123            CL_list.Add(l); // line 7 of Algorithm 2
124            CL_selected[l] = true; // line 7 of Algorithm 2
125            // incrementally updating location weights
126            foreach (var k in L)
127              H[k] += capacities[k] * capacities[l] / distances[k, l];
128
129            T = new List<int>(WhereDemandEqualOrLess(F, GetMaximumSlack(slack, CL_selected), demands)); // line 8 of Algorithm 2
130          }
131          if (T.Count > 0) { // line 10 of Algorithm 2
132            // W is the proportion that an equipment is chosen
133            var WW = T.Select(x => W[x]);
134            var f = T.SampleProportional(random, 1, WW, false, false) // line 11 of Algorithm 2
135              .Single();
136            T.Remove(f); // line 12 of Algorithm 2
137            F.Remove(f); // line 12 of Algorithm 2
138            CF.Add(f); // line 12 of Algorithm 2
139            var R = WhereSlackGreaterOrEqual(CL_list, demands[f], slack).ToList(); // line 13 of Algorithm 2
140            // Z is the proportion that a location is chosen in stage 2
141            var l = R[0];
142            if (R.Count > 1) { // optimization, calculate probabilistic weights only in case |R| > 1
143              Array.Clear(Z, 0, R.Count);
144              var zk = 0;
145              foreach (var k in R) {
146                // d is an increase in fitness if f would be assigned to location k
147                var d = installCosts[f, k];
148                foreach (var i in CF) {
149                  if (assignment[i] == 0) continue; // i is unassigned
150                  var j = assignment[i] - 1;
151                  d += transportCosts * weights[f, i] * distances[k, j];
152                }
153                foreach (var h in CL_list) {
154                  if (k == h) continue;
155                  Z[zk] += slack[k] * capacities[h] / (d * distances[k, h]);
156                }
157                zk++;
158              }
159              l = R.SampleProportional(random, 1, Z.Take(R.Count), false, false).Single(); // line 14 of Algorithm 2
160            }
161            assignment[f] = l + 1; // line 15 of Algorithm 2
162            slack[l] -= demands[f];
163            T = new List<int>(WhereDemandEqualOrLess(F, GetMaximumSlack(slack, CL_selected), demands)); // line 16 of Algorithm 2
164            threshold = 1.0 - (double)T.Count / Math.Max(F.Count, 1.0); // line 17 of Algorithm 2
165          }
166        } while (T.Count > 0 || L.Count > 0); // line 19 of Algorithm 2
167
168        if (maximumTries > 0) tries++;
169
170        if (F.Count == 0) {
171          bestAssignment = assignment.Select(x => x - 1).ToArray();
172          break;
173        } else if (createMostFeasibleSolution) {
174          // complete the solution and remember the one with least violation
175          foreach (var l in L.ToArray()) {
176            CL_list.Add(l);
177            CL_selected[l] = true;
178            L.Remove(l);
179          }
180          while (F.Count > 0) {
181            var f = F.Select((v, i) => new { Index = i, Value = v }).MaxItems(x => demands[x.Value]).SampleRandom(random);
182            var l = CL_list.MaxItems(x => slack[x]).SampleRandom(random);
183            F.RemoveAt(f.Index);
184            assignment[f.Value] = l + 1;
185            slack[l] -= demands[f.Value];
186          }
187          double violation = slack.Select(x => x < 0 ? -x : 0).Sum();
188          if (violation < minViolation) {
189            bestAssignment = assignment.Select(x => x - 1).ToArray();
190            minViolation = violation;
191          }
192        }
193      }
194
195      if (bestAssignment == null)
196        throw new InvalidOperationException(String.Format("No solution could be found in {0} tries.", maximumTries));
197
198      return new IntegerVector(bestAssignment);
199    }
200
201    protected override IntegerVector CreateRandomSolution(IRandom random, GQAPInstance problemInstance) {
202      return CreateSolution(random, problemInstance,
203        MaximumTriesParameter.ActualValue.Value,
204        CreateMostFeasibleSolutionParameter.ActualValue.Value,
205        CancellationToken);
206    }
207
208    private static IEnumerable<int> WhereDemandEqualOrLess(IEnumerable<int> facilities, double maximum, DoubleArray demands) {
209      foreach (int f in facilities) {
210        if (demands[f] <= maximum) yield return f;
211      }
212    }
213
214    private static double GetMaximumSlack(double[] slack, bool[] CL) {
215      var max = double.MinValue;
216      for (var i = 0; i < slack.Length; i++) {
217        if (CL[i] && max < slack[i]) max = slack[i];
218      }
219      return max;
220    }
221
222    private static IEnumerable<int> WhereSlackGreaterOrEqual(IEnumerable<int> locations, double minimum, double[] slack) {
223      foreach (int l in locations) {
224        if (slack[l] >= minimum) yield return l;
225      }
226    }
227  }
228}
Note: See TracBrowser for help on using the repository browser.