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

Last change on this file since 15713 was 15713, checked in by abeham, 22 months ago

#1614:

  • added additional constraint to benchmark data generator and updated one instance that was affected by this
  • added fitness landscape characteristics for the GQAP
  • fixed RLD analysis view to compensate for empty convergence graphs
  • fixed CPLEX solvers not using the obj value when the solver terminates (callback is not called if proven optimal solution is found)
  • added code for local solver to also check on final quality
File size: 10.2 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 HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.IntegerVectorEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.GeneralizedQuadraticAssignment;
33using HeuristicLab.Random;
34
35namespace HeuristicLab.Analysis.FitnessLandscape {
36  [Item("Directed Walk (GQAP-specific)", "")]
37  [StorableClass]
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(bool deserializing) : base(deserializing) { }
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()) yield break;
137
138      var start = iter.Current;
139      while (iter.MoveNext()) {
140        var end = iter.Current;
141
142        var walk = (bestImprovement ? BestDirectedWalk(gqap, start, end) : FirstDirectedWalk(random, gqap, start, end)).ToList();
143        yield return walk.ToList();
144        start = end;
145      } // end paths
146    }
147
148    private static IEnumerable<Tuple<IntegerVector, double>> BestDirectedWalk(GQAP gqap, IntegerVector start, IntegerVector end) {
149      var N = gqap.ProblemInstance.Demands.Length;
150      var sol = start;
151      var evaluation = gqap.ProblemInstance.Evaluate(start);
152      var fitness = gqap.ProblemInstance.ToSingleObjective(evaluation);
153      yield return Tuple.Create(sol, fitness);
154     
155      var reassignments = Enumerable.Range(0, N).Select(x => {
156        if (start[x] == end[x]) return null;
157        var r = new int[N];
158        r[x] = end[x] + 1;
159        return r;
160      }).ToArray();
161      var indices = Enumerable.Range(0, N).Select(x => start[x] == end[x] ? null : new List<int>(1) { x }).ToArray();
162
163      for (var step = 0; step < N; step++) {
164        var bestFitness = double.MaxValue;
165        Evaluation bestEvaluation = null;
166        var bestIndex = -1;
167        sol = (IntegerVector)sol.Clone();
168       
169        for (var index = 0; index < N; index++) {
170          if (sol[index] == end[index]) continue;
171
172          var oneMove = new NMove(reassignments[index], indices[index]);
173          var eval = GQAPNMoveEvaluator.Evaluate(oneMove, sol, evaluation, gqap.ProblemInstance);
174          var fit = gqap.ProblemInstance.ToSingleObjective(eval);
175          if (fit < bestFitness) { // QAP is minimization
176            bestFitness = fit;
177            bestEvaluation = eval;
178            bestIndex = index;
179          }
180        }
181        if (bestIndex >= 0) {
182          sol[bestIndex] = end[bestIndex];
183          fitness = bestFitness;
184          evaluation = bestEvaluation;
185          yield return Tuple.Create(sol, fitness);
186        } else break;
187      }
188    }
189
190    private static IEnumerable<Tuple<IntegerVector, double>> FirstDirectedWalk(IRandom random, GQAP gqap, IntegerVector start, IntegerVector end) {
191      var N = gqap.ProblemInstance.Demands.Length;
192      var sol = start;
193      var evaluation = gqap.ProblemInstance.Evaluate(start);
194      var fitness = gqap.ProblemInstance.ToSingleObjective(evaluation);
195      yield return Tuple.Create(sol, fitness);
196
197      var reassignments = Enumerable.Range(0, N).Select(x => {
198        if (start[x] == end[x]) return null;
199        var r = new int[N];
200        r[x] = end[x] + 1;
201        return r;
202      }).ToArray();
203      var indices = Enumerable.Range(0, N).Select(x => start[x] == end[x] ? null : new List<int>(1) { x }).ToArray();
204
205      // randomize the order in which improvements are tried
206      var order = Enumerable.Range(0, N).Shuffle(random).ToArray();
207
208      for (var step = 0; step < N; step++) {
209        var bestFitness = double.MaxValue;
210        Evaluation bestEvaluation = null;
211        var bestIndex = -1;
212        sol = (IntegerVector)sol.Clone();
213        for (var i = 0; i < N; i++) {
214          var index = order[i];
215          if (sol[index] == end[index]) continue;
216
217          var oneMove = new NMove(reassignments[index], indices[index]);
218          var eval = GQAPNMoveEvaluator.Evaluate(oneMove, sol, evaluation, gqap.ProblemInstance);
219          var fit = gqap.ProblemInstance.ToSingleObjective(eval);
220
221          if (fit < bestFitness) { // GQAP is minimization
222            bestFitness = fit;
223            bestEvaluation = evaluation;
224            bestIndex = index;
225            if (fit < fitness) break;
226          }
227        }
228        if (bestIndex >= 0) {
229          sol[bestIndex] = end[bestIndex];
230          fitness = bestFitness;
231          evaluation = bestEvaluation;
232          yield return Tuple.Create(sol, fitness);
233        } else break;
234      }
235    }
236  }
237}
Note: See TracBrowser for help on using the repository browser.