source: branches/PerformanceComparison/HeuristicLab.Analysis.FitnessLandscape/3.3/ProblemCharacteristicAnalysis/QAP/QAPDirectedWalk.cs @ 15031

Last change on this file since 15031 was 15031, checked in by abeham, 3 years ago

#2457: worked on code for eurocast paper

File size: 10.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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 HeuristicLab.Common;
23using HeuristicLab.Core;
24using HeuristicLab.Data;
25using HeuristicLab.Encodings.PermutationEncoding;
26using HeuristicLab.Optimization;
27using HeuristicLab.Parameters;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29using HeuristicLab.Problems.QuadraticAssignment;
30using HeuristicLab.Random;
31using System;
32using System.Collections.Generic;
33using System.Linq;
34using System.Threading;
35
36namespace HeuristicLab.Analysis.FitnessLandscape {
37  [Item("Directed Walk (QAP-specific)", "")]
38  [StorableClass]
39  public class QAPDirectedWalk : CharacteristicCalculator {
40   
41    public IFixedValueParameter<IntValue> PathsParameter {
42      get { return (IFixedValueParameter<IntValue>)Parameters["Paths"]; }
43    }
44
45    public IFixedValueParameter<BoolValue> BestImprovementParameter {
46      get { return (IFixedValueParameter<BoolValue>)Parameters["BestImprovement"]; }
47    }
48
49    public IValueParameter<IntValue> SeedParameter {
50      get { return (IValueParameter<IntValue>)Parameters["Seed"]; }
51    }
52
53    public IFixedValueParameter<BoolValue> LocalOptimaParameter {
54      get { return (IFixedValueParameter<BoolValue>)Parameters["LocalOptima"]; }
55    }
56
57    public int Paths {
58      get { return PathsParameter.Value.Value; }
59      set { PathsParameter.Value.Value = value; }
60    }
61
62    public bool BestImprovement {
63      get { return BestImprovementParameter.Value.Value; }
64      set { BestImprovementParameter.Value.Value = value; }
65    }
66
67    public int? Seed {
68      get { return SeedParameter.Value != null ? SeedParameter.Value.Value : (int?)null; }
69      set { SeedParameter.Value = value.HasValue ? new IntValue(value.Value) : null; }
70    }
71
72    public bool LocalOptima {
73      get { return LocalOptimaParameter.Value.Value; }
74      set { LocalOptimaParameter.Value.Value = value; }
75    }
76
77    [StorableConstructor]
78    private QAPDirectedWalk(bool deserializing) : base(deserializing) { }
79    private QAPDirectedWalk(QAPDirectedWalk original, Cloner cloner) : base(original, cloner) { }
80    public QAPDirectedWalk() {
81      characteristics.AddRange(new[] { "Swap2.Sharpness", "Swap2.Bumpiness", "Swap2.Flatness" }
82        .Select(x => new StringValue(x)).ToList());
83      Parameters.Add(new FixedValueParameter<IntValue>("Paths", "The number of paths to explore (a path is a set of solutions that connect two randomly chosen solutions).", new IntValue(50)));
84      Parameters.Add(new FixedValueParameter<BoolValue>("BestImprovement", "Whether the best of all alternatives should be chosen for each step in the path or just the first improving (least degrading) move should be made.", new BoolValue(true)));
85      Parameters.Add(new OptionalValueParameter<IntValue>("Seed", "The seed for the random number generator."));
86      Parameters.Add(new FixedValueParameter<BoolValue>("LocalOptima", "Whether to perform walks between local optima.", new BoolValue(false)));
87    }
88
89    public override IDeepCloneable Clone(Cloner cloner) {
90      return new QAPDirectedWalk(this, cloner);
91    }
92
93    public override bool CanCalculate() {
94      return Problem is QuadraticAssignmentProblem;
95    }
96
97    public override IEnumerable<IResult> Calculate() {
98      IRandom random = Seed.HasValue ? new MersenneTwister((uint)Seed.Value) : new MersenneTwister();
99      var qap = (QuadraticAssignmentProblem)Problem;
100      List<Permutation> permutations = CalculateRelinkingPoints(random, qap, Paths, LocalOptima);
101
102      var trajectories = Run(random, (QuadraticAssignmentProblem)Problem, permutations, BestImprovement).ToList();
103      var result = PermutationPathAnalysis.GetCharacteristics(trajectories);
104
105      foreach (var chara in characteristics.CheckedItems.Select(x => x.Value.Value)) {
106        if (chara == "Swap2.Sharpness") yield return new Result("Swap2.Sharpness", new DoubleValue(result.Sharpness));
107        if (chara == "Swap2.Bumpiness") yield return new Result("Swap2.Bumpiness", new DoubleValue(result.Bumpiness));
108        if (chara == "Swap2.Flatness") yield return new Result("Swap2.Flatness", new DoubleValue(result.Flatness));
109      }
110    }
111
112    public static List<Permutation> CalculateRelinkingPoints(IRandom random, QuadraticAssignmentProblem qap, int pathCount, bool localOptima) {
113      var perm = new Permutation(PermutationTypes.Absolute, qap.Weights.Rows, random);
114      if (localOptima) {
115        var fit = new DoubleValue(QAPEvaluator.Apply(perm, qap.Weights, qap.Distances));
116        QAPExhaustiveSwap2LocalImprovement.ImproveFast(perm, qap.Weights, qap.Distances, fit, new IntValue(0), new IntValue(0), qap.Maximization.Value, int.MaxValue, CancellationToken.None);
117      }
118      var permutations = new List<Permutation> { perm };
119      while (permutations.Count < pathCount + 1) {
120        perm = (Permutation)permutations.Last().Clone();
121        BiasedShuffle(perm, random);
122        if (localOptima) {
123          var fit = new DoubleValue(QAPEvaluator.Apply(perm, qap.Weights, qap.Distances));
124          QAPExhaustiveSwap2LocalImprovement.ImproveFast(perm, qap.Weights, qap.Distances, fit, new IntValue(0), new IntValue(0), qap.Maximization.Value, int.MaxValue, CancellationToken.None);
125        }
126        if (HammingSimilarityCalculator.CalculateSimilarity(permutations.Last(), perm) < 0.75)
127          permutations.Add(perm);
128      }
129
130      return permutations;
131    }
132
133    public static IEnumerable<List<Tuple<Permutation, double>>> Run(IRandom random, QuadraticAssignmentProblem qap, IEnumerable<Permutation> permutations, bool bestImprovement = true) {
134      var iter = permutations.GetEnumerator();
135      if (!iter.MoveNext()) yield break;
136
137      var min = qap.LowerBound.Value;
138      var max = qap.AverageQuality.Value;
139
140      var start = iter.Current;
141      while (iter.MoveNext()) {
142        var end = iter.Current;
143
144        var walk = (bestImprovement ? BestDirectedWalk(qap, start, end) : FirstDirectedWalk(random, qap, start, end)).ToList();
145        yield return walk.Select(x => Tuple.Create(x.Item1, (x.Item2 - min) / (max - min))).ToList();
146        start = end;
147      } // end paths
148    }
149
150    private static IEnumerable<Tuple<Permutation, double>> BestDirectedWalk(QuadraticAssignmentProblem qap, Permutation start, Permutation end) {
151      var N = qap.Weights.Rows;
152      var sol = start;
153      var fitness = QAPEvaluator.Apply(sol, qap.Weights, qap.Distances);
154      yield return Tuple.Create(sol, fitness);
155
156      var invSol = GetInverse(sol);
157      // we require at most N-1 steps to move from one permutation to another
158      for (var step = 0; step < N - 1; step++) {
159        var bestFitness = double.MaxValue;
160        var bestIndex = -1;
161        sol = (Permutation)sol.Clone();
162        for (var index = 0; index < N; index++) {
163          if (sol[index] == end[index]) continue;
164          var fit = QAPSwap2MoveEvaluator.Apply(sol, new Swap2Move(index, invSol[end[index]]), qap.Weights, qap.Distances);
165          if (fit < bestFitness) { // QAP is minimization
166            bestFitness = fit;
167            bestIndex = index;
168          }
169        }
170        if (bestIndex >= 0) {
171          var prev = sol[bestIndex];
172          Swap2Manipulator.Apply(sol, bestIndex, invSol[end[bestIndex]]);
173          fitness += bestFitness;
174          yield return Tuple.Create(sol, fitness);
175          invSol[prev] = invSol[end[bestIndex]];
176          invSol[sol[bestIndex]] = bestIndex;
177        } else break;
178      }
179    }
180
181    private static IEnumerable<Tuple<Permutation, double>> FirstDirectedWalk(IRandom random, QuadraticAssignmentProblem qap, Permutation start, Permutation end) {
182      var N = qap.Weights.Rows;
183      var sol = start;
184      var fitness = QAPEvaluator.Apply(sol, qap.Weights, qap.Distances);
185      yield return Tuple.Create(sol, fitness);
186
187      var invSol = GetInverse(sol);
188      // randomize the order in which improvements are tried
189      var order = Enumerable.Range(0, N).Shuffle(random).ToArray();
190      // we require at most N-1 steps to move from one permutation to another
191      for (var step = 0; step < N - 1; step++) {
192        var bestFitness = double.MaxValue;
193        var bestIndex = -1;
194        sol = (Permutation)sol.Clone();
195        for (var i = 0; i < N; i++) {
196          var index = order[i];
197          if (sol[index] == end[index]) continue;
198          var fit = QAPSwap2MoveEvaluator.Apply(sol, new Swap2Move(index, invSol[end[index]]), qap.Weights, qap.Distances);
199          if (fit < bestFitness) { // QAP is minimization
200            bestFitness = fit;
201            bestIndex = index;
202            if (bestFitness < 0) break;
203          }
204        }
205        if (bestIndex >= 0) {
206          var prev = sol[bestIndex];
207          Swap2Manipulator.Apply(sol, bestIndex, invSol[end[bestIndex]]);
208          fitness += bestFitness;
209          yield return Tuple.Create(sol, fitness);
210          invSol[prev] = invSol[end[bestIndex]];
211          invSol[sol[bestIndex]] = bestIndex;
212        } else break;
213      }
214    }
215
216    private static int[] GetInverse(Permutation p) {
217      var inv = new int[p.Length];
218      for (var i = 0; i < p.Length; i++) {
219        inv[p[i]] = i;
220      }
221      return inv;
222    }
223
224    // permutation must be strictly different in every position
225    private static void BiasedShuffle(Permutation p, IRandom random) {
226      for (var i = p.Length - 1; i > 0; i--) {
227        // Swap element "i" with a random earlier element (excluding itself)
228        var swapIndex = random.Next(i);
229        var h = p[swapIndex];
230        p[swapIndex] = p[i];
231        p[i] = h;
232      }
233    }
234  }
235}
Note: See TracBrowser for help on using the repository browser.