Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1614_GeneralizedQAP/HeuristicLab.Analysis.FitnessLandscape/3.3/ProblemCharacteristicAnalysis/GQAP/GQAPDirectedWalk.cs @ 17573

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

#1614: updated to new persistence and .NET 4.6.1

File size: 10.5 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 System;
23using System.Collections.Generic;
24using System.Linq;
25using HEAL.Attic;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.IntegerVectorEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Problems.GeneralizedQuadraticAssignment;
33using HeuristicLab.Random;
34
35namespace HeuristicLab.Analysis.FitnessLandscape {
36  [Item("Directed Walk (GQAP-specific)", "")]
37  [StorableType("333209A4-8EE7-4944-8A23-CBF120627DBE")]
38  public class GQAPDirectedWalk : CharacteristicCalculator {
39   
40    public IFixedValueParameter<IntValue> PathsParameter {
41      get { return (IFixedValueParameter<IntValue>)Parameters["Paths"]; }
42    }
43
44    public IFixedValueParameter<BoolValue> BestImprovementParameter {
45      get { return (IFixedValueParameter<BoolValue>)Parameters["BestImprovement"]; }
46    }
47
48    public IValueParameter<IntValue> SeedParameter {
49      get { return (IValueParameter<IntValue>)Parameters["Seed"]; }
50    }
51
52    public IFixedValueParameter<BoolValue> LocalOptimaParameter {
53      get { return (IFixedValueParameter<BoolValue>)Parameters["LocalOptima"]; }
54    }
55
56    public int Paths {
57      get { return PathsParameter.Value.Value; }
58      set { PathsParameter.Value.Value = value; }
59    }
60
61    public bool BestImprovement {
62      get { return BestImprovementParameter.Value.Value; }
63      set { BestImprovementParameter.Value.Value = value; }
64    }
65
66    public int? Seed {
67      get { return SeedParameter.Value != null ? SeedParameter.Value.Value : (int?)null; }
68      set { SeedParameter.Value = value.HasValue ? new IntValue(value.Value) : null; }
69    }
70
71    public bool LocalOptima {
72      get { return LocalOptimaParameter.Value.Value; }
73      set { LocalOptimaParameter.Value.Value = value; }
74    }
75
76    [StorableConstructor]
77    private GQAPDirectedWalk(StorableConstructorFlag _) : base(_) { }
78    private GQAPDirectedWalk(GQAPDirectedWalk original, Cloner cloner) : base(original, cloner) { }
79    public GQAPDirectedWalk() {
80      characteristics.AddRange(new[] { "1Shift.Sharpness", "1Shift.Bumpiness", "1Shift.Flatness" }
81        .Select(x => new StringValue(x)).ToList());
82      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)));
83      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)));
84      Parameters.Add(new OptionalValueParameter<IntValue>("Seed", "The seed for the random number generator."));
85      Parameters.Add(new FixedValueParameter<BoolValue>("LocalOptima", "Whether to perform walks between local optima.", new BoolValue(false)));
86    }
87
88    public override IDeepCloneable Clone(Cloner cloner) {
89      return new GQAPDirectedWalk(this, cloner);
90    }
91
92    public override bool CanCalculate() {
93      return Problem is GQAP;
94    }
95
96    public override IEnumerable<IResult> Calculate() {
97      IRandom random = Seed.HasValue ? new MersenneTwister((uint)Seed.Value) : new MersenneTwister();
98      var gqap = (GQAP)Problem;
99      List<IntegerVector> assignments = CalculateRelinkingPoints(random, gqap, Paths, LocalOptima);
100
101      var trajectories = Run(random, (GQAP)Problem, assignments, BestImprovement).ToList();
102      var result = IntegerVectorPathAnalysis.GetCharacteristics(trajectories);
103
104      foreach (var chara in characteristics.CheckedItems.Select(x => x.Value.Value)) {
105        if (chara == "1Shift.Sharpness") yield return new Result("1Shift.Sharpness", new DoubleValue(result.Sharpness));
106        if (chara == "1Shift.Bumpiness") yield return new Result("1Shift.Bumpiness", new DoubleValue(result.Bumpiness));
107        if (chara == "1Shift.Flatness") yield return new Result("1Shift.Flatness", new DoubleValue(result.Flatness));
108      }
109    }
110
111    public static List<IntegerVector> CalculateRelinkingPoints(IRandom random, GQAP gqap, int pathCount, bool localOptima) {
112      var assign = new IntegerVector(gqap.ProblemInstance.Demands.Length, random, 0, gqap.ProblemInstance.Capacities.Length);
113      if (localOptima) {
114        var eval = gqap.ProblemInstance.Evaluate(assign);
115        var fit = gqap.ProblemInstance.ToSingleObjective(eval);
116        OneOptLocalSearch.Apply(random, assign, ref fit, ref eval, gqap.ProblemInstance, out var evals);
117      }
118      var points = new List<IntegerVector> { assign };
119      while (points.Count < pathCount + 1) {
120        assign = (IntegerVector)points.Last().Clone();
121        RelocateEquipmentManipluator.Apply(random, assign, gqap.ProblemInstance.Capacities.Length, 0);
122        if (localOptima) {
123          var eval = gqap.ProblemInstance.Evaluate(assign);
124          var fit = gqap.ProblemInstance.ToSingleObjective(eval);
125          OneOptLocalSearch.Apply(random, assign, ref fit, ref eval, gqap.ProblemInstance, out var evals);
126        }
127        if (HammingSimilarityCalculator.CalculateSimilarity(points.Last(), assign) < 0.75)
128          points.Add(assign);
129      }
130
131      return points;
132    }
133
134    public static IEnumerable<List<Tuple<IntegerVector, double>>> Run(IRandom random, GQAP gqap, IEnumerable<IntegerVector> points, bool bestImprovement = true) {
135      var iter = points.GetEnumerator();
136      if (!iter.MoveNext()) return new List<Tuple<IntegerVector, double>>[0];
137
138      var start = iter.Current;
139      var walks = new List<List<Tuple<IntegerVector, double>>>();
140      while (iter.MoveNext()) {
141        var end = iter.Current;
142
143        var walk = (bestImprovement ? BestDirectedWalk(gqap, start, end) : FirstDirectedWalk(random, gqap, start, end)).ToList();
144        walks.Add(walk);
145        start = end;
146      } // end paths
147
148      var min = walks.SelectMany(x => x.Select(y => y.Item2)).Min();
149      var max = walks.SelectMany(x => x.Select(y => y.Item2)).Max();
150
151      if (min == max) max = min + 1;
152      return walks.Select(w => w.Select(x => Tuple.Create(x.Item1, (x.Item2 - min) / (max - min))).ToList());
153    }
154
155    private static IEnumerable<Tuple<IntegerVector, double>> BestDirectedWalk(GQAP gqap, IntegerVector start, IntegerVector end) {
156      var N = gqap.ProblemInstance.Demands.Length;
157      var sol = start;
158      var evaluation = gqap.ProblemInstance.Evaluate(start);
159      var fitness = gqap.ProblemInstance.ToSingleObjective(evaluation);
160      yield return Tuple.Create(sol, fitness);
161     
162      var reassignments = Enumerable.Range(0, N).Select(x => {
163        if (start[x] == end[x]) return null;
164        var r = new int[N];
165        r[x] = end[x] + 1;
166        return r;
167      }).ToArray();
168      var indices = Enumerable.Range(0, N).Select(x => start[x] == end[x] ? null : new List<int>(1) { x }).ToArray();
169
170      for (var step = 0; step < N; step++) {
171        var bestFitness = double.MaxValue;
172        Evaluation bestEvaluation = null;
173        var bestIndex = -1;
174        sol = (IntegerVector)sol.Clone();
175       
176        for (var index = 0; index < N; index++) {
177          if (sol[index] == end[index]) continue;
178
179          var oneMove = new NMove(reassignments[index], indices[index]);
180          var eval = GQAPNMoveEvaluator.Evaluate(oneMove, sol, evaluation, gqap.ProblemInstance);
181          var fit = gqap.ProblemInstance.ToSingleObjective(eval);
182          if (fit < bestFitness) { // QAP is minimization
183            bestFitness = fit;
184            bestEvaluation = eval;
185            bestIndex = index;
186          }
187        }
188        if (bestIndex >= 0) {
189          sol[bestIndex] = end[bestIndex];
190          fitness = bestFitness;
191          evaluation = bestEvaluation;
192          yield return Tuple.Create(sol, fitness);
193        } else break;
194      }
195    }
196
197    private static IEnumerable<Tuple<IntegerVector, double>> FirstDirectedWalk(IRandom random, GQAP gqap, IntegerVector start, IntegerVector end) {
198      var N = gqap.ProblemInstance.Demands.Length;
199      var sol = start;
200      var evaluation = gqap.ProblemInstance.Evaluate(start);
201      var fitness = gqap.ProblemInstance.ToSingleObjective(evaluation);
202      yield return Tuple.Create(sol, fitness);
203
204      var reassignments = Enumerable.Range(0, N).Select(x => {
205        if (start[x] == end[x]) return null;
206        var r = new int[N];
207        r[x] = end[x] + 1;
208        return r;
209      }).ToArray();
210      var indices = Enumerable.Range(0, N).Select(x => start[x] == end[x] ? null : new List<int>(1) { x }).ToArray();
211
212      // randomize the order in which improvements are tried
213      var order = Enumerable.Range(0, N).Shuffle(random).ToArray();
214
215      for (var step = 0; step < N; step++) {
216        var bestFitness = double.MaxValue;
217        Evaluation bestEvaluation = null;
218        var bestIndex = -1;
219        sol = (IntegerVector)sol.Clone();
220        for (var i = 0; i < N; i++) {
221          var index = order[i];
222          if (sol[index] == end[index]) continue;
223
224          var oneMove = new NMove(reassignments[index], indices[index]);
225          var eval = GQAPNMoveEvaluator.Evaluate(oneMove, sol, evaluation, gqap.ProblemInstance);
226          var fit = gqap.ProblemInstance.ToSingleObjective(eval);
227
228          if (fit < bestFitness) { // GQAP is minimization
229            bestFitness = fit;
230            bestEvaluation = evaluation;
231            bestIndex = index;
232            if (fit < fitness) break;
233          }
234        }
235        if (bestIndex >= 0) {
236          sol[bestIndex] = end[bestIndex];
237          fitness = bestFitness;
238          evaluation = bestEvaluation;
239          yield return Tuple.Create(sol, fitness);
240        } else break;
241      }
242    }
243  }
244}
Note: See TracBrowser for help on using the repository browser.