Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1614: restructured architecture to allow for different evaluator with different penalty strategies

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