Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment/3.3/Operators/Crossovers/GQAPPathRelinking.cs @ 15490

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

#1614:

  • branched optimization
  • adapted references
  • renamed plugin
File size: 14.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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 HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.IntegerVectorEncoding;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Random;
32
33namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment {
34  [Item("GQAPPathRelinking", "Operator that performs path relinking between two solutions. It is 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.")]
35  [StorableClass]
36  public class GQAPPathRelinking : GQAPCrossover, IQualitiesAwareGQAPOperator, IDemandsAwareGQAPOperator, ICapacitiesAwareGQAPOperator,
37  IWeightsAwareGQAPOperator, IDistancesAwareGQAPOperator, IInstallationCostsAwareGQAPOperator, ITransportationCostsAwareGQAPOperator,
38  IExpectedRandomQualityAwareGQAPOperator, IEvaluatorAwareGQAPOperator {
39
40    public ILookupParameter<BoolValue> MaximizationParameter {
41      get { return (ILookupParameter<BoolValue>)Parameters["Maximization"]; }
42    }
43    public IScopeTreeLookupParameter<DoubleValue> QualityParameter {
44      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }
45    }
46    public IScopeTreeLookupParameter<DoubleValue> FlowDistanceQualityParameter {
47      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters["FlowDistanceQuality"]; }
48    }
49    public IScopeTreeLookupParameter<DoubleValue> InstallationQualityParameter {
50      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters["InstallationQuality"]; }
51    }
52    public IScopeTreeLookupParameter<DoubleValue> OverbookedCapacityParameter {
53      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters["OverbookedCapacity"]; }
54    }
55    public ILookupParameter<DoubleArray> DemandsParameter {
56      get { return (ILookupParameter<DoubleArray>)Parameters["Demands"]; }
57    }
58    public ILookupParameter<DoubleArray> CapacitiesParameter {
59      get { return (ILookupParameter<DoubleArray>)Parameters["Capacities"]; }
60    }
61    public ILookupParameter<DoubleMatrix> WeightsParameter {
62      get { return (ILookupParameter<DoubleMatrix>)Parameters["Weights"]; }
63    }
64    public ILookupParameter<DoubleMatrix> DistancesParameter {
65      get { return (ILookupParameter<DoubleMatrix>)Parameters["Distances"]; }
66    }
67    public ILookupParameter<DoubleMatrix> InstallationCostsParameter {
68      get { return (ILookupParameter<DoubleMatrix>)Parameters["InstallationCosts"]; }
69    }
70    public IValueLookupParameter<DoubleValue> TransportationCostsParameter {
71      get { return (IValueLookupParameter<DoubleValue>)Parameters["TransportationCosts"]; }
72    }
73    public IValueLookupParameter<DoubleValue> ExpectedRandomQualityParameter {
74      get { return (IValueLookupParameter<DoubleValue>)Parameters["ExpectedRandomQuality"]; }
75    }
76    public IValueLookupParameter<IGQAPEvaluator> EvaluatorParameter {
77      get { return (IValueLookupParameter<IGQAPEvaluator>)Parameters["Evaluator"]; }
78    }
79
80    public IValueParameter<PercentValue> CandidateSizeFactorParameter {
81      get { return (IValueParameter<PercentValue>)Parameters["CandidateSizeFactor"]; }
82    }
83
84    [StorableConstructor]
85    protected GQAPPathRelinking(bool deserializing) : base(deserializing) { }
86    protected GQAPPathRelinking(GQAPPathRelinking original, Cloner cloner) : base(original, cloner) { }
87    public GQAPPathRelinking()
88      : base() {
89      Parameters.Add(new LookupParameter<BoolValue>("Maximization", GeneralizedQuadraticAssignmentProblem.MaximizationDescription));
90      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", GQAPEvaluator.QualityDescription));
91      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("FlowDistanceQuality", GQAPEvaluator.FlowDistanceQualityDescription));
92      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("InstallationQuality", GQAPEvaluator.InstallationQualityDescription));
93      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("OverbookedCapacity", GQAPEvaluator.OverbookedCapacityDescription));
94      Parameters.Add(new LookupParameter<DoubleArray>("Demands", GeneralizedQuadraticAssignmentProblem.DemandsDescription));
95      Parameters.Add(new LookupParameter<DoubleArray>("Capacities", GeneralizedQuadraticAssignmentProblem.CapacitiesDescription));
96      Parameters.Add(new LookupParameter<DoubleMatrix>("Weights", GeneralizedQuadraticAssignmentProblem.WeightsDescription));
97      Parameters.Add(new LookupParameter<DoubleMatrix>("Distances", GeneralizedQuadraticAssignmentProblem.DistancesDescription));
98      Parameters.Add(new LookupParameter<DoubleMatrix>("InstallationCosts", GeneralizedQuadraticAssignmentProblem.InstallationCostsDescription));
99      Parameters.Add(new ValueLookupParameter<DoubleValue>("TransportationCosts", GeneralizedQuadraticAssignmentProblem.TransportationCostsDescription));
100      Parameters.Add(new ValueLookupParameter<DoubleValue>("ExpectedRandomQuality", GeneralizedQuadraticAssignmentProblem.ExpectedRandomQualityDescription));
101      Parameters.Add(new ValueLookupParameter<IGQAPEvaluator>("Evaluator", "The evaluator that is used to evaluate GQAP solutions."));
102      Parameters.Add(new ValueParameter<PercentValue>("CandidateSizeFactor", "(η) Determines the size of the set of feasible moves in each path-relinking step relative to the maximum size. A value of 50% means that only half of all possible moves are considered each step.", new PercentValue(0.5)));
103    }
104
105    public override IDeepCloneable Clone(Cloner cloner) {
106      return new GQAPPathRelinking(this, cloner);
107    }
108
109    public static IntegerVector Apply(IRandom random, ItemArray<IntegerVector> parents, BoolValue maximization, ItemArray<DoubleValue> qualities,
110      ItemArray<DoubleValue> flowDistanceQualities, ItemArray<DoubleValue> installationQualities, ItemArray<DoubleValue> overbookedCapacities,
111      DoubleArray demands, DoubleArray capacities, DoubleMatrix weights, DoubleMatrix distances, DoubleMatrix installationCosts,
112      DoubleValue transportationCosts, DoubleValue expectedRandomQuality, DoubleValue candidateSizeFactor, IGQAPEvaluator evaluator) {
113      if (random == null) throw new ArgumentNullException("random", "No IRandom provider is given.");
114      if (parents == null || !parents.Any()) throw new ArgumentException("No parents given for path relinking.", "parents");
115      if (parents.Length != 2) throw new ArgumentException(String.Format("Two parents were expected for path relinking, but {0} was/were given.", parents.Length.ToString()), "parents");
116      if (parents[0].Length != parents[1].Length) throw new ArgumentException("The length of the parents is not equal.", "parents");
117      if (qualities == null || qualities.Length == 0) throw new ArgumentException("The qualities are not given.", "qualities");
118      if (qualities.Length != parents.Length) throw new ArgumentException(String.Format("There are a different number of parents ({0}) than quality values ({1})", parents.Length.ToString(), qualities.Length.ToString()));
119
120      var source = parents[0];
121      var target = parents[1];
122      IntegerVector result;
123      double resultQuality, resultFDQ, resultIQ, resultOC;
124
125      int betterParent = 1;
126      if ((maximization.Value && qualities[0].Value >= qualities[1].Value)
127        || (!maximization.Value && qualities[0].Value <= qualities[1].Value))
128        betterParent = 0;
129
130      result = (IntegerVector)parents[betterParent].Clone();
131      resultQuality = qualities[betterParent].Value;
132      resultFDQ = flowDistanceQualities[betterParent].Value;
133      resultIQ = installationQualities[betterParent].Value;
134      resultOC = overbookedCapacities[betterParent].Value;
135
136      var pi_prime = (IntegerVector)source.Clone();
137      var fix = new HashSet<int>();
138      var nonFix = new HashSet<int>(Enumerable.Range(0, demands.Length));
139      var phi = new HashSet<int>((pi_prime.GetDifferingIndices(target)));
140
141      while (phi.Any()) {
142        var B = new List<GQAPSolution>();
143        foreach (var v in phi) {
144          int oldLocation = pi_prime[v];
145          pi_prime[v] = target[v];
146          var pi2 = makeFeasible(random, pi_prime, v, nonFix, demands, capacities);
147          pi_prime[v] = oldLocation;
148
149          double currentFDQ, currentIQ, currentOC;
150          evaluator.Evaluate(pi2, weights, distances, installationCosts, demands, capacities,
151            out currentFDQ, out currentIQ, out currentOC);
152
153          if (currentOC <= 0.0) {
154            var quality = evaluator.GetFitness(currentFDQ, currentIQ, currentOC,
155              transportationCosts.Value, expectedRandomQuality.Value);
156            var solution = new GQAPSolution(pi2, new DoubleValue(quality), new DoubleValue(currentFDQ),
157              new DoubleValue(currentIQ), new DoubleValue(currentOC));
158            if (B.Count >= candidateSizeFactor.Value * phi.Count) {
159              int mostSimilarIndex = -1;
160              double mostSimilarValue = 1.0;
161              for (int i = 0; i < B.Count; i++) {
162                if (IsBetter(maximization.Value, solution.Quality.Value, B[i].Quality.Value)) {
163                  var similarity = HammingSimilarityCalculator.CalculateSimilarity(solution.Assignment, B[i].Assignment);
164                  if (similarity == 1.0) {
165                    mostSimilarIndex = -1;
166                    break;
167                  } else if (similarity < mostSimilarValue) {
168                    mostSimilarValue = similarity;
169                    mostSimilarIndex = i;
170                  }
171                }
172              }
173              if (mostSimilarIndex >= 0)
174                B[mostSimilarIndex] = solution;
175            } else {
176              bool contains = false;
177              foreach (var b in B) {
178                if (!solution.Assignment.GetDifferingIndices(b.Assignment).Any()) {
179                  contains = true;
180                  break;
181                }
182              }
183              if (!contains) B.Add(solution);
184            }
185          }
186        }
187        if (B.Any()) {
188          GQAPSolution pi;
189          if (maximization.Value) pi = B.SampleProportional(random, 1, B.Select(x => x.Quality.Value), false).First();
190          else pi = B.SampleProportional(random, 1, B.Select(x => 1.0 / x.Quality.Value), false).First();
191          var diff = pi.Assignment.GetDifferingIndices(target);
192          var I = phi.Except(diff);
193          var i = I.SampleRandom(random);
194          fix.Add(i);
195          nonFix.Remove(i);
196          pi_prime = pi.Assignment;
197          if (IsBetter(maximization.Value, pi.Quality.Value, resultQuality)) {
198            result = pi.Assignment;
199            resultQuality = pi.Quality.Value;
200            resultFDQ = pi.FlowDistanceQuality.Value;
201            resultIQ = pi.InstallationQuality.Value;
202            resultOC = pi.OverbookedCapacity.Value;
203          }
204        } else return result;
205        phi = new HashSet<int>(pi_prime.GetDifferingIndices(target));
206      }
207
208      return result;
209    }
210
211    protected override IntegerVector Cross(IRandom random, ItemArray<IntegerVector> parents) {
212      return Apply(random, parents, MaximizationParameter.ActualValue, QualityParameter.ActualValue, FlowDistanceQualityParameter.ActualValue,
213        InstallationQualityParameter.ActualValue, OverbookedCapacityParameter.ActualValue, DemandsParameter.ActualValue,
214        CapacitiesParameter.ActualValue, WeightsParameter.ActualValue, DistancesParameter.ActualValue,
215        InstallationCostsParameter.ActualValue, TransportationCostsParameter.ActualValue,
216        ExpectedRandomQualityParameter.ActualValue, CandidateSizeFactorParameter.Value,
217        EvaluatorParameter.ActualValue);
218    }
219
220    private static IntegerVector makeFeasible(IRandom random, IntegerVector assignment, int equipment, HashSet<int> nonFix, DoubleArray demands, DoubleArray capacities, int maximumTries = 1000) {
221      int l = assignment[equipment];
222      var slack = ComputeSlack(assignment, demands, capacities);
223      if (slack[l] >= 0) return (IntegerVector)assignment.Clone();
224
225      IntegerVector result = null;
226      int k = 0;
227      while (k < maximumTries && slack[l] < 0) {
228        result = (IntegerVector)assignment.Clone();
229        do {
230          var maxSlack = slack.Max();
231          var T = nonFix.Where(x => x != equipment && assignment[x] == l && demands[x] <= maxSlack);
232          if (T.Any()) {
233            int i = T.SampleProportional(random, 1, T.Select(x => demands[x]), false).First();
234            var j = Enumerable.Range(0, capacities.Length).Where(x => slack[x] >= demands[i]).SampleRandom(random);
235            result[i] = j;
236            slack[j] -= demands[i];
237            slack[l] += demands[i];
238          } else break;
239        } while (slack[l] < 0);
240        k++;
241      }
242      return result;
243    }
244
245    private static DoubleArray ComputeSlack(IntegerVector assignment, DoubleArray demands, DoubleArray capacities) {
246      var slack = (DoubleArray)capacities.Clone();
247      for (int i = 0; i < assignment.Length; i++) {
248        slack[assignment[i]] -= demands[i];
249      }
250      return slack;
251    }
252
253    private static bool IsBetter(bool maximization, double quality, double otherQuality) {
254      return maximization && quality > otherQuality || !maximization && quality < otherQuality;
255    }
256  }
257}
Note: See TracBrowser for help on using the repository browser.