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
RevLine 
[7373]1#region License Information
2/* HeuristicLab
[16728]3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[7373]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
[7407]22using System;
[7373]23using System.Collections.Generic;
24using System.Linq;
[7593]25using System.Threading;
[7373]26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.IntegerVectorEncoding;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[7813]32using HeuristicLab.Random;
[16728]33using HEAL.Attic;
[7373]34
[7407]35namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment {
[15555]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>
[7373]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.")]
[16728]40  [StorableType("44919EFC-AF47-4F0D-8EE4-F5AECBF776CA")]
[15504]41  public class GreedyRandomizedSolutionCreator : GQAPStochasticSolutionCreator {
[7373]42
43    public IValueLookupParameter<IntValue> MaximumTriesParameter {
44      get { return (IValueLookupParameter<IntValue>)Parameters["MaximumTries"]; }
45    }
[7593]46    public IValueLookupParameter<BoolValue> CreateMostFeasibleSolutionParameter {
47      get { return (IValueLookupParameter<BoolValue>)Parameters["CreateMostFeasibleSolution"]; }
48    }
[7373]49
50    [StorableConstructor]
[16728]51    protected GreedyRandomizedSolutionCreator(StorableConstructorFlag _) : base(_) { }
[7373]52    protected GreedyRandomizedSolutionCreator(GreedyRandomizedSolutionCreator original, Cloner cloner)
53      : base(original, cloner) { }
54    public GreedyRandomizedSolutionCreator()
55      : base() {
[7593]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)));
[7373]58    }
59
60    public override IDeepCloneable Clone(Cloner cloner) {
61      return new GreedyRandomizedSolutionCreator(this, cloner);
62    }
63
[15504]64    public static IntegerVector CreateSolution(IRandom random, GQAPInstance problemInstance,
[7970]65      int maximumTries, bool createMostFeasibleSolution, CancellationToken cancelToken) {
[15555]66      var weights = problemInstance.Weights;
67      var distances = problemInstance.Distances;
[15558]68      var installCosts = problemInstance.InstallationCosts;
[15504]69      var demands = problemInstance.Demands;
[15553]70      var capacities = problemInstance.Capacities.ToArray();
[15555]71      var transportCosts = problemInstance.TransportationCosts;
[15553]72      var equipments = demands.Length;
73      var locations = capacities.Length;
[7593]74      int tries = 0;
[15553]75      var slack = new double[locations];
[7593]76      double minViolation = double.MaxValue;
[15558]77      int[] assignment = null;
[15553]78      int[] bestAssignment = null;
[15555]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
[15553]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
[15555]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
[15558]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      }
[15555]96
[7593]97      while (maximumTries <= 0 || tries < maximumTries) {
98        cancelToken.ThrowIfCancellationRequested();
99
[15558]100        assignment = new int[equipments];
101
[15555]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
[7593]107
[15555]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
[15553]110
[15558]111        Array.Clear(H, 0, H.Length);
112
[15555]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
[15558]120            var HH = L.Select(x => H[x]);
[15555]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
[15558]125            // incrementally updating location weights
126            foreach (var k in L)
127              H[k] += capacities[k] * capacities[l] / distances[k, l];
128
[15555]129            T = new List<int>(WhereDemandEqualOrLess(F, GetMaximumSlack(slack, CL_selected), demands)); // line 8 of Algorithm 2
[7407]130          }
[15555]131          if (T.Count > 0) { // line 10 of Algorithm 2
132            // W is the proportion that an equipment is chosen
[15558]133            var WW = T.Select(x => W[x]);
134            var f = T.SampleProportional(random, 1, WW, false, false) // line 11 of Algorithm 2
[15555]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
[15558]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++;
[15555]158              }
[15558]159              l = R.SampleProportional(random, 1, Z.Take(R.Count), false, false).Single(); // line 14 of Algorithm 2
[15555]160            }
161            assignment[f] = l + 1; // line 15 of Algorithm 2
[7407]162            slack[l] -= demands[f];
[15555]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
[7407]165          }
[15555]166        } while (T.Count > 0 || L.Count > 0); // line 19 of Algorithm 2
167
[7593]168        if (maximumTries > 0) tries++;
[15555]169
[15553]170        if (F.Count == 0) {
[15555]171          bestAssignment = assignment.Select(x => x - 1).ToArray();
[7593]172          break;
173        } else if (createMostFeasibleSolution) {
174          // complete the solution and remember the one with least violation
[7833]175          foreach (var l in L.ToArray()) {
[15553]176            CL_list.Add(l);
177            CL_selected[l] = true;
[7833]178            L.Remove(l);
179          }
[15553]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];
[7593]186          }
[15504]187          double violation = slack.Select(x => x < 0 ? -x : 0).Sum();
[7593]188          if (violation < minViolation) {
[15555]189            bestAssignment = assignment.Select(x => x - 1).ToArray();
[7593]190            minViolation = violation;
191          }
192        }
[7373]193      }
194
[15555]195      if (bestAssignment == null)
[15553]196        throw new InvalidOperationException(String.Format("No solution could be found in {0} tries.", maximumTries));
[7407]197
[15555]198      return new IntegerVector(bestAssignment);
[7373]199    }
[7407]200
[15504]201    protected override IntegerVector CreateRandomSolution(IRandom random, GQAPInstance problemInstance) {
202      return CreateSolution(random, problemInstance,
[7593]203        MaximumTriesParameter.ActualValue.Value,
204        CreateMostFeasibleSolutionParameter.ActualValue.Value,
205        CancellationToken);
206    }
207
[15553]208    private static IEnumerable<int> WhereDemandEqualOrLess(IEnumerable<int> facilities, double maximum, DoubleArray demands) {
[7407]209      foreach (int f in facilities) {
210        if (demands[f] <= maximum) yield return f;
211      }
212    }
213
[15553]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;
[7407]220    }
221
[15553]222    private static IEnumerable<int> WhereSlackGreaterOrEqual(IEnumerable<int> locations, double minimum, double[] slack) {
[7407]223      foreach (int l in locations) {
224        if (slack[l] >= minimum) yield return l;
225      }
226    }
[7373]227  }
228}
Note: See TracBrowser for help on using the repository browser.