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 |
|
---|
22 | using HeuristicLab.Common;
|
---|
23 | using HeuristicLab.Core;
|
---|
24 | using HeuristicLab.Data;
|
---|
25 | using HeuristicLab.Encodings.PermutationEncoding;
|
---|
26 | using HeuristicLab.Optimization;
|
---|
27 | using HeuristicLab.Parameters;
|
---|
28 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
29 | using HeuristicLab.Problems.QuadraticAssignment;
|
---|
30 | using HeuristicLab.Random;
|
---|
31 | using System;
|
---|
32 | using System.Collections.Generic;
|
---|
33 | using System.Linq;
|
---|
34 | using System.Threading;
|
---|
35 |
|
---|
36 | namespace 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", /*"Swap2.Steadiness"*/ }
|
---|
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 | var pathCount = Paths;
|
---|
101 |
|
---|
102 | var perm = new Permutation(PermutationTypes.Absolute, qap.Weights.Rows, random);
|
---|
103 | if (LocalOptima) {
|
---|
104 | var fit = new DoubleValue(QAPEvaluator.Apply(perm, qap.Weights, qap.Distances));
|
---|
105 | QAPExhaustiveSwap2LocalImprovement.ImproveFast(perm, qap.Weights, qap.Distances, fit, new IntValue(0), new IntValue(0), qap.Maximization.Value, int.MaxValue, CancellationToken.None);
|
---|
106 | }
|
---|
107 | var permutations = new List<Permutation> { perm };
|
---|
108 | while (permutations.Count < pathCount + 1) {
|
---|
109 | perm = (Permutation)permutations.Last().Clone();
|
---|
110 | BiasedShuffle(perm, random);
|
---|
111 | if (LocalOptima) {
|
---|
112 | var fit = new DoubleValue(QAPEvaluator.Apply(perm, qap.Weights, qap.Distances));
|
---|
113 | QAPExhaustiveSwap2LocalImprovement.ImproveFast(perm, qap.Weights, qap.Distances, fit, new IntValue(0), new IntValue(0), qap.Maximization.Value, int.MaxValue, CancellationToken.None);
|
---|
114 | }
|
---|
115 | if (HammingSimilarityCalculator.CalculateSimilarity(permutations.Last(), perm) < 0.75)
|
---|
116 | permutations.Add(perm);
|
---|
117 | }
|
---|
118 |
|
---|
119 | var trajectories = Run(random, (QuadraticAssignmentProblem)Problem, permutations, BestImprovement).ToList();
|
---|
120 | var result = PermutationPathAnalysis.GetCharacteristics(trajectories);
|
---|
121 |
|
---|
122 | foreach (var chara in characteristics.CheckedItems.Select(x => x.Value.Value)) {
|
---|
123 | if (chara == "Swap2.Sharpness") yield return new Result("Swap2.Sharpness", new DoubleValue(result.Sharpness));
|
---|
124 | if (chara == "Swap2.Bumpiness") yield return new Result("Swap2.Bumpiness", new DoubleValue(result.Bumpiness));
|
---|
125 | if (chara == "Swap2.Flatness") yield return new Result("Swap2.Flatness", new DoubleValue(result.Flatness));
|
---|
126 | }
|
---|
127 | }
|
---|
128 |
|
---|
129 | public static IEnumerable<List<Tuple<Permutation, double>>> Run(IRandom random, QuadraticAssignmentProblem qap, IEnumerable<Permutation> permutations, bool bestImprovement = true) {
|
---|
130 | var iter = permutations.GetEnumerator();
|
---|
131 | if (!iter.MoveNext()) yield break;
|
---|
132 |
|
---|
133 | var min = qap.LowerBound.Value;
|
---|
134 | var max = qap.AverageQuality.Value;
|
---|
135 |
|
---|
136 | var start = iter.Current;
|
---|
137 | while (iter.MoveNext()) {
|
---|
138 | var end = iter.Current;
|
---|
139 |
|
---|
140 | var walk = (bestImprovement ? BestDirectedWalk(qap, start, end) : FirstDirectedWalk(random, qap, start, end)).ToList();
|
---|
141 | yield return walk.Select(x => Tuple.Create(x.Item1, (x.Item2 - min) / (max - min))).ToList();
|
---|
142 | start = end;
|
---|
143 | } // end paths
|
---|
144 | }
|
---|
145 |
|
---|
146 | private static IEnumerable<Tuple<Permutation, double>> BestDirectedWalk(QuadraticAssignmentProblem qap, Permutation start, Permutation end) {
|
---|
147 | var N = qap.Weights.Rows;
|
---|
148 | var sol = start;
|
---|
149 | var fitness = QAPEvaluator.Apply(sol, qap.Weights, qap.Distances);
|
---|
150 | yield return Tuple.Create(sol, fitness);
|
---|
151 |
|
---|
152 | var invSol = GetInverse(sol);
|
---|
153 | // we require at most N-1 steps to move from one permutation to another
|
---|
154 | for (var step = 0; step < N - 1; step++) {
|
---|
155 | var bestFitness = double.MaxValue;
|
---|
156 | var bestIndex = -1;
|
---|
157 | sol = (Permutation)sol.Clone();
|
---|
158 | for (var index = 0; index < N; index++) {
|
---|
159 | if (sol[index] == end[index]) continue;
|
---|
160 | var fit = QAPSwap2MoveEvaluator.Apply(sol, new Swap2Move(index, invSol[end[index]]), qap.Weights, qap.Distances);
|
---|
161 | if (fit < bestFitness) { // QAP is minimization
|
---|
162 | bestFitness = fit;
|
---|
163 | bestIndex = index;
|
---|
164 | }
|
---|
165 | }
|
---|
166 | if (bestIndex >= 0) {
|
---|
167 | var prev = sol[bestIndex];
|
---|
168 | Swap2Manipulator.Apply(sol, bestIndex, invSol[end[bestIndex]]);
|
---|
169 | fitness += bestFitness;
|
---|
170 | yield return Tuple.Create(sol, fitness);
|
---|
171 | invSol[prev] = invSol[end[bestIndex]];
|
---|
172 | invSol[sol[bestIndex]] = bestIndex;
|
---|
173 | } else break;
|
---|
174 | }
|
---|
175 | }
|
---|
176 |
|
---|
177 | private static IEnumerable<Tuple<Permutation, double>> FirstDirectedWalk(IRandom random, QuadraticAssignmentProblem qap, Permutation start, Permutation end) {
|
---|
178 | var N = qap.Weights.Rows;
|
---|
179 | var sol = start;
|
---|
180 | var fitness = QAPEvaluator.Apply(sol, qap.Weights, qap.Distances);
|
---|
181 | yield return Tuple.Create(sol, fitness);
|
---|
182 |
|
---|
183 | var invSol = GetInverse(sol);
|
---|
184 | // randomize the order in which improvements are tried
|
---|
185 | var order = Enumerable.Range(0, N).Shuffle(random).ToArray();
|
---|
186 | // we require at most N-1 steps to move from one permutation to another
|
---|
187 | for (var step = 0; step < N - 1; step++) {
|
---|
188 | var bestFitness = double.MaxValue;
|
---|
189 | var bestIndex = -1;
|
---|
190 | sol = (Permutation)sol.Clone();
|
---|
191 | for (var i = 0; i < N; i++) {
|
---|
192 | var index = order[i];
|
---|
193 | if (sol[index] == end[index]) continue;
|
---|
194 | var fit = QAPSwap2MoveEvaluator.Apply(sol, new Swap2Move(index, invSol[end[index]]), qap.Weights, qap.Distances);
|
---|
195 | if (fit < bestFitness) { // QAP is minimization
|
---|
196 | bestFitness = fit;
|
---|
197 | bestIndex = index;
|
---|
198 | if (bestFitness < 0) break;
|
---|
199 | }
|
---|
200 | }
|
---|
201 | if (bestIndex >= 0) {
|
---|
202 | var prev = sol[bestIndex];
|
---|
203 | Swap2Manipulator.Apply(sol, bestIndex, invSol[end[bestIndex]]);
|
---|
204 | fitness += bestFitness;
|
---|
205 | yield return Tuple.Create(sol, fitness);
|
---|
206 | invSol[prev] = invSol[end[bestIndex]];
|
---|
207 | invSol[sol[bestIndex]] = bestIndex;
|
---|
208 | } else break;
|
---|
209 | }
|
---|
210 | }
|
---|
211 |
|
---|
212 | private static int[] GetInverse(Permutation p) {
|
---|
213 | var inv = new int[p.Length];
|
---|
214 | for (var i = 0; i < p.Length; i++) {
|
---|
215 | inv[p[i]] = i;
|
---|
216 | }
|
---|
217 | return inv;
|
---|
218 | }
|
---|
219 |
|
---|
220 | // permutation must be strictly different in every position
|
---|
221 | private static void BiasedShuffle(Permutation p, IRandom random) {
|
---|
222 | for (var i = p.Length - 1; i > 0; i--) {
|
---|
223 | // Swap element "i" with a random earlier element (excluding itself)
|
---|
224 | var swapIndex = random.Next(i);
|
---|
225 | var h = p[swapIndex];
|
---|
226 | p[swapIndex] = p[i];
|
---|
227 | p[i] = h;
|
---|
228 | }
|
---|
229 | }
|
---|
230 | }
|
---|
231 | }
|
---|