Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7813 was 7813, checked in by abeham, 12 years ago

#1614

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