Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1614: updated to new persistence and .NET 4.6.1

File size: 10.5 KB
RevLine 
[13861]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
[15713]22using System;
23using System.Collections.Generic;
24using System.Linq;
[16728]25using HEAL.Attic;
[13861]26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
[15713]29using HeuristicLab.Encodings.IntegerVectorEncoding;
[13861]30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
[15713]32using HeuristicLab.Problems.GeneralizedQuadraticAssignment;
[13861]33using HeuristicLab.Random;
34
[14678]35namespace HeuristicLab.Analysis.FitnessLandscape {
[15713]36  [Item("Directed Walk (GQAP-specific)", "")]
[16728]37  [StorableType("333209A4-8EE7-4944-8A23-CBF120627DBE")]
[15713]38  public class GQAPDirectedWalk : CharacteristicCalculator {
[13861]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
[14690]52    public IFixedValueParameter<BoolValue> LocalOptimaParameter {
53      get { return (IFixedValueParameter<BoolValue>)Parameters["LocalOptima"]; }
54    }
55
[13861]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
[14690]71    public bool LocalOptima {
72      get { return LocalOptimaParameter.Value.Value; }
73      set { LocalOptimaParameter.Value.Value = value; }
74    }
75
[13861]76    [StorableConstructor]
[16728]77    private GQAPDirectedWalk(StorableConstructorFlag _) : base(_) { }
[15713]78    private GQAPDirectedWalk(GQAPDirectedWalk original, Cloner cloner) : base(original, cloner) { }
79    public GQAPDirectedWalk() {
80      characteristics.AddRange(new[] { "1Shift.Sharpness", "1Shift.Bumpiness", "1Shift.Flatness" }
[13861]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."));
[14690]85      Parameters.Add(new FixedValueParameter<BoolValue>("LocalOptima", "Whether to perform walks between local optima.", new BoolValue(false)));
[13861]86    }
87
88    public override IDeepCloneable Clone(Cloner cloner) {
[15713]89      return new GQAPDirectedWalk(this, cloner);
[13861]90    }
91
92    public override bool CanCalculate() {
[15713]93      return Problem is GQAP;
[13861]94    }
95
96    public override IEnumerable<IResult> Calculate() {
[14429]97      IRandom random = Seed.HasValue ? new MersenneTwister((uint)Seed.Value) : new MersenneTwister();
[15713]98      var gqap = (GQAP)Problem;
99      List<IntegerVector> assignments = CalculateRelinkingPoints(random, gqap, Paths, LocalOptima);
[13861]100
[15713]101      var trajectories = Run(random, (GQAP)Problem, assignments, BestImprovement).ToList();
102      var result = IntegerVectorPathAnalysis.GetCharacteristics(trajectories);
[15031]103
104      foreach (var chara in characteristics.CheckedItems.Select(x => x.Value.Value)) {
[15713]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));
[15031]108      }
109    }
110
[15713]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);
[15031]113      if (localOptima) {
[15713]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);
[14690]117      }
[15713]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);
[15031]122        if (localOptima) {
[15713]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);
[14690]126        }
[15713]127        if (HammingSimilarityCalculator.CalculateSimilarity(points.Last(), assign) < 0.75)
128          points.Add(assign);
[14429]129      }
[13861]130
[15713]131      return points;
[14429]132    }
[13861]133
[15713]134    public static IEnumerable<List<Tuple<IntegerVector, double>>> Run(IRandom random, GQAP gqap, IEnumerable<IntegerVector> points, bool bestImprovement = true) {
135      var iter = points.GetEnumerator();
[15718]136      if (!iter.MoveNext()) return new List<Tuple<IntegerVector, double>>[0];
[13861]137
[14429]138      var start = iter.Current;
[15718]139      var walks = new List<List<Tuple<IntegerVector, double>>>();
[14429]140      while (iter.MoveNext()) {
141        var end = iter.Current;
[13861]142
[15713]143        var walk = (bestImprovement ? BestDirectedWalk(gqap, start, end) : FirstDirectedWalk(random, gqap, start, end)).ToList();
[15718]144        walks.Add(walk);
[14429]145        start = end;
146      } // end paths
[15718]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());
[14429]153    }
[13861]154
[15713]155    private static IEnumerable<Tuple<IntegerVector, double>> BestDirectedWalk(GQAP gqap, IntegerVector start, IntegerVector end) {
156      var N = gqap.ProblemInstance.Demands.Length;
[13861]157      var sol = start;
[15713]158      var evaluation = gqap.ProblemInstance.Evaluate(start);
159      var fitness = gqap.ProblemInstance.ToSingleObjective(evaluation);
[14429]160      yield return Tuple.Create(sol, fitness);
[15713]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();
[14429]169
[15713]170      for (var step = 0; step < N; step++) {
[13861]171        var bestFitness = double.MaxValue;
[15713]172        Evaluation bestEvaluation = null;
[13861]173        var bestIndex = -1;
[15713]174        sol = (IntegerVector)sol.Clone();
175       
[13861]176        for (var index = 0; index < N; index++) {
177          if (sol[index] == end[index]) continue;
[15713]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);
[13861]182          if (fit < bestFitness) { // QAP is minimization
183            bestFitness = fit;
[15713]184            bestEvaluation = eval;
[13861]185            bestIndex = index;
186          }
187        }
188        if (bestIndex >= 0) {
[15713]189          sol[bestIndex] = end[bestIndex];
190          fitness = bestFitness;
191          evaluation = bestEvaluation;
[13861]192          yield return Tuple.Create(sol, fitness);
193        } else break;
194      }
195    }
196
[15713]197    private static IEnumerable<Tuple<IntegerVector, double>> FirstDirectedWalk(IRandom random, GQAP gqap, IntegerVector start, IntegerVector end) {
198      var N = gqap.ProblemInstance.Demands.Length;
[13861]199      var sol = start;
[15713]200      var evaluation = gqap.ProblemInstance.Evaluate(start);
201      var fitness = gqap.ProblemInstance.ToSingleObjective(evaluation);
[14429]202      yield return Tuple.Create(sol, fitness);
203
[15713]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
[13861]212      // randomize the order in which improvements are tried
213      var order = Enumerable.Range(0, N).Shuffle(random).ToArray();
[15713]214
215      for (var step = 0; step < N; step++) {
[13861]216        var bestFitness = double.MaxValue;
[15713]217        Evaluation bestEvaluation = null;
[13861]218        var bestIndex = -1;
[15713]219        sol = (IntegerVector)sol.Clone();
[13861]220        for (var i = 0; i < N; i++) {
221          var index = order[i];
222          if (sol[index] == end[index]) continue;
[15713]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
[13861]229            bestFitness = fit;
[15713]230            bestEvaluation = evaluation;
[13861]231            bestIndex = index;
[15713]232            if (fit < fitness) break;
[13861]233          }
234        }
235        if (bestIndex >= 0) {
[15713]236          sol[bestIndex] = end[bestIndex];
237          fitness = bestFitness;
238          evaluation = bestEvaluation;
[13861]239          yield return Tuple.Create(sol, fitness);
240        } else break;
241      }
242    }
243  }
244}
Note: See TracBrowser for help on using the repository browser.