Free cookie consent management tool by TermsFeed Policy Generator

source: branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/LinearLinkage/LinearLinkageMemPR.cs @ 14471

Last change on this file since 14471 was 14471, checked in by abeham, 8 years ago

#2701:

  • Updated GraphColoringProblem and Problems.Instances
    • Added new fitness function from literature
    • Added DIMACS benchmark instances
  • Updated LinearLinkageEncoding
    • Added HammingSimilarityCalculator
File size: 14.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 System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Threading;
26using HeuristicLab.Algorithms.MemPR.Interfaces;
27using HeuristicLab.Algorithms.MemPR.Util;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Encodings.LinearLinkageEncoding;
31using HeuristicLab.Optimization;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Random;
35
36namespace HeuristicLab.Algorithms.MemPR.LinearLinkage {
37  [Item("MemPR (linear linkage)", "MemPR implementation for linear linkage vectors.")]
38  [StorableClass]
39  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 999)]
40  public class LinearLinkageMemPR : MemPRAlgorithm<SingleObjectiveBasicProblem<LinearLinkageEncoding>, Encodings.LinearLinkageEncoding.LinearLinkage, LinearLinkageMemPRPopulationContext, LinearLinkageMemPRSolutionContext> {
41    private const double UncommonBitSubsetMutationProbabilityMagicConst = 0.05;
42   
43    [StorableConstructor]
44    protected LinearLinkageMemPR(bool deserializing) : base(deserializing) { }
45    protected LinearLinkageMemPR(LinearLinkageMemPR original, Cloner cloner) : base(original, cloner) { }
46    public LinearLinkageMemPR() {
47      foreach (var trainer in ApplicationManager.Manager.GetInstances<ISolutionModelTrainer<LinearLinkageMemPRPopulationContext>>())
48        SolutionModelTrainerParameter.ValidValues.Add(trainer);
49     
50      foreach (var localSearch in ApplicationManager.Manager.GetInstances<ILocalSearch<LinearLinkageMemPRSolutionContext>>()) {
51        LocalSearchParameter.ValidValues.Add(localSearch);
52      }
53    }
54
55    public override IDeepCloneable Clone(Cloner cloner) {
56      return new LinearLinkageMemPR(this, cloner);
57    }
58
59    protected override bool Eq(ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> a, ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> b) {
60      var s1 = a.Solution;
61      var s2 = b.Solution;
62      if (s1.Length != s2.Length) return false;
63      for (var i = 0; i < s1.Length; i++)
64        if (s1[i] != s2[i]) return false;
65      return true;
66    }
67
68    protected override double Dist(ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> a, ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> b) {
69      return HammingSimilarityCalculator.CalculateSimilarity(a.Solution, b.Solution);
70    }
71
72    protected override ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> ToScope(Encodings.LinearLinkageEncoding.LinearLinkage code, double fitness = double.NaN) {
73      var creator = Problem.SolutionCreator as ILinearLinkageCreator;
74      if (creator == null) throw new InvalidOperationException("Can only solve linear linkage encoded problems with MemPR (linear linkage)");
75      return new SingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage>(code, creator.LLEParameter.ActualName, fitness, Problem.Evaluator.QualityParameter.ActualName) {
76        Parent = Context.Scope
77      };
78    }
79
80    protected override ISolutionSubspace<Encodings.LinearLinkageEncoding.LinearLinkage> CalculateSubspace(IEnumerable<Encodings.LinearLinkageEncoding.LinearLinkage> solutions, bool inverse = false) {
81      var pop = solutions.ToList();
82      var N = pop[0].Length;
83      var subspace = new bool[N];
84      for (var i = 0; i < N; i++) {
85        var val = pop[0][i];
86        if (inverse) subspace[i] = true;
87        for (var p = 1; p < pop.Count; p++) {
88          if (pop[p][i] != val) subspace[i] = !inverse;
89        }
90      }
91      return new LinearLinkageSolutionSubspace(subspace);
92    }
93
94    protected override int TabuWalk(ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> scope, int maxEvals, CancellationToken token, ISolutionSubspace<Encodings.LinearLinkageEncoding.LinearLinkage> subspace = null) {
95      return 0;
96      /*Func<Encodings.LinearLinkageEncoding.LinearLinkage, IRandom, double> eval = new EvaluationWrapper<Encodings.LinearLinkageEncoding.LinearLinkage>(Context.Problem, scope).Evaluate;
97      var quality = scope.Fitness;
98      var lle = scope.Solution;
99      var random = Context.Random;
100      var evaluations = 0;
101      var maximization = Context.Problem.Maximization;
102      if (double.IsNaN(quality)) {
103        quality = eval(lle, random);
104        evaluations++;
105      }
106      Encodings.LinearLinkageEncoding.LinearLinkage bestOfTheWalk = null;
107      double bestOfTheWalkF = double.NaN;
108      var current = (Encodings.LinearLinkageEncoding.LinearLinkage)lle.Clone();
109      var currentF = quality;
110      var overallImprovement = false;
111      var tabu = new double[current.Length, current.Length];
112      for (var i = 0; i < current.Length; i++) {
113        for (var j = i; j < current.Length; j++) {
114          tabu[i, j] = tabu[j, i] = double.MaxValue;
115        }
116        tabu[i, current[i]] = currentF;
117      }
118
119      var steps = 0;
120      var stepsUntilBestOfWalk = 0;
121      for (var iter = 0; iter < int.MaxValue; iter++) {
122        var allTabu = true;
123        var bestOfTheRestF = double.NaN;
124        object bestOfTheRest = null;
125        var improved = false;
126        foreach () {
127          if (subspace != null && !(subspace[swap.Index1, 0] && subspace[swap.Index2, 0]))
128            continue;
129
130
131          var q = eval(current, random);
132          evaluations++;
133          if (FitnessComparer.IsBetter(maximization, q, quality)) {
134            overallImprovement = true;
135            quality = q;
136            for (var i = 0; i < current.Length; i++) lle[i] = current[i];
137          }
138          // check if it would not be an improvement to swap these into their positions
139          var isTabu = !FitnessComparer.IsBetter(maximization, q, tabu[swap.Index1, current[swap.Index1]])
140                    && !FitnessComparer.IsBetter(maximization, q, tabu[swap.Index2, current[swap.Index2]]);
141          if (!isTabu) allTabu = false;
142          if (FitnessComparer.IsBetter(maximization, q, currentF) && !isTabu) {
143            if (FitnessComparer.IsBetter(maximization, q, bestOfTheWalkF)) {
144              bestOfTheWalk = (Encodings.LinearLinkageEncoding.LinearLinkage)current.Clone();
145              bestOfTheWalkF = q;
146              stepsUntilBestOfWalk = steps;
147            }
148            steps++;
149            improved = true;
150            // perform the move
151            currentF = q;
152            // mark that to move them to their previous position requires to make an improvement
153            tabu[swap.Index1, current[swap.Index2]] = maximization ? Math.Max(q, tabu[swap.Index1, current[swap.Index2]])
154                                                                   : Math.Min(q, tabu[swap.Index1, current[swap.Index2]]);
155            tabu[swap.Index2, current[swap.Index1]] = maximization ? Math.Max(q, tabu[swap.Index2, current[swap.Index1]])
156                                                                   : Math.Min(q, tabu[swap.Index2, current[swap.Index1]]);
157          } else { // undo the move
158            if (!isTabu && FitnessComparer.IsBetter(maximization, q, bestOfTheRestF)) {
159              bestOfTheRest = swap;
160              bestOfTheRestF = q;
161            }
162            current[swap.Index2] = current[swap.Index1];
163            current[swap.Index1] = h;
164          }
165          if (evaluations >= maxEvals) break;
166        }
167        if (!allTabu && !improved && bestOfTheRest != null) {
168          tabu[bestOfTheRest.Index1, current[bestOfTheRest.Index1]] = maximization ? Math.Max(currentF, tabu[bestOfTheRest.Index1, current[bestOfTheRest.Index1]])
169                                                                                   : Math.Min(currentF, tabu[bestOfTheRest.Index1, current[bestOfTheRest.Index1]]);
170          tabu[bestOfTheRest.Index2, current[bestOfTheRest.Index2]] = maximization ? Math.Max(currentF, tabu[bestOfTheRest.Index2, current[bestOfTheRest.Index2]])
171                                                                                   : Math.Min(currentF, tabu[bestOfTheRest.Index2, current[bestOfTheRest.Index2]]);
172
173          var h = current[bestOfTheRest.Index1];
174          current[bestOfTheRest.Index1] = current[bestOfTheRest.Index2];
175          current[bestOfTheRest.Index2] = h;
176
177          currentF = bestOfTheRestF;
178          steps++;
179        } else if (allTabu) break;
180        if (evaluations >= maxEvals) break;
181      }
182      Context.IncrementEvaluatedSolutions(evaluations);
183      if (!overallImprovement && bestOfTheWalk != null) {
184        quality = bestOfTheWalkF;
185        for (var i = 0; i < current.Length; i++) lle[i] = bestOfTheWalk[i];
186      }
187      return stepsUntilBestOfWalk;*/
188    }
189
190    protected override ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> Cross(ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> p1Scope, ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> p2Scope, CancellationToken token) {
191      var p1 = p1Scope.Solution;
192      var p2 = p2Scope.Solution;
193      var transfered = new bool[p1.Length];
194      var subspace = new bool[p1.Length];
195      var lleeChild = new int[p1.Length];
196      var lleep1 = p1.ToLLEe();
197      var lleep2 = p2.ToLLEe();
198      for (var i = p1.Length - 1; i >= 0; i--) {
199        // Step 1
200        subspace[i] = p1[i] != p2[i];
201        var p1IsEnd = p1[i] == i;
202        var p2IsEnd = p2[i] == i;
203        if (p1IsEnd & p2IsEnd) {
204          transfered[i] = true;
205        } else if (p1IsEnd | p2IsEnd) {
206          transfered[i] = Context.Random.NextDouble() < 0.5;
207        }
208        lleeChild[i] = i;
209
210        // Step 2
211        if (transfered[i]) continue;
212        var end1 = lleep1[i];
213        var end2 = lleep2[i];
214        var containsEnd1 = transfered[end1];
215        var containsEnd2 = transfered[end2];
216        if (containsEnd1 & containsEnd2) {
217          if (Context.Random.NextDouble() < 0.5) {
218            lleeChild[i] = end1;
219          } else {
220            lleeChild[i] = end2;
221          }
222        } else if (containsEnd1) {
223          lleeChild[i] = end1;
224        } else if (containsEnd2) {
225          lleeChild[i] = end2;
226        } else {
227          if (Context.Random.NextDouble() < 0.5) {
228            lleeChild[i] = lleeChild[p1[i]];
229          } else {
230            lleeChild[i] = lleeChild[p2[i]];
231          }
232        }
233      }
234      var child = new Encodings.LinearLinkageEncoding.LinearLinkage(lleeChild.Length);
235      child.FromLLEe(lleeChild);
236     
237      return ToScope(child);
238    }
239
240    protected override void Mutate(ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> offspring, CancellationToken token, ISolutionSubspace<Encodings.LinearLinkageEncoding.LinearLinkage> subspace = null) {
241      var lle = offspring.Solution;
242      var subset = subspace is LinearLinkageSolutionSubspace ? ((LinearLinkageSolutionSubspace)subspace).Subspace : null;
243      for (var i = 0; i < lle.Length - 1; i++) {
244        if (subset == null || subset[i]) continue; // mutation works against crossover so aims to mutate noTouch points
245        if (Context.Random.NextDouble() < UncommonBitSubsetMutationProbabilityMagicConst) {
246          subset[i] = true;
247          var index = Context.Random.Next(i, lle.Length);
248          for (var j = index - 1; j >= i; j--) {
249            if (lle[j] == index) index = j;
250          }
251          lle[i] = index;
252          index = i;
253          var idx2 = i;
254          for (var j = i - 1; j >= 0; j--) {
255            if (lle[j] == lle[index]) {
256              lle[j] = idx2;
257              index = idx2 = j;
258            } else if (lle[j] == idx2) idx2 = j;
259          }
260        }
261      }
262    }
263
264    protected override ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> Relink(ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> a, ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage> b, CancellationToken token) {
265      var maximization = Context.Problem.Maximization;
266      if (double.IsNaN(a.Fitness)) {
267        Evaluate(a, token);
268        Context.IncrementEvaluatedSolutions(1);
269      }
270      if (double.IsNaN(b.Fitness)) {
271        Evaluate(b, token);
272        Context.IncrementEvaluatedSolutions(1);
273      }
274      var child = (ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage>)a.Clone();
275      var cgroups = child.Solution.GetGroups().Select(x => new HashSet<int>(x)).ToList();
276      var g2 = b.Solution.GetGroups().ToList();
277      var order = Enumerable.Range(0, g2.Count).Shuffle(Context.Random).ToList();
278      ISingleObjectiveSolutionScope <Encodings.LinearLinkageEncoding.LinearLinkage> bestChild = null;
279      for (var j = 0; j < g2.Count; j++) {
280        var g = g2[order[j]];
281        var changed = false;
282        for (var k = j; k < cgroups.Count; k++) {
283          foreach (var f in g) if (cgroups[k].Remove(f)) changed = true;
284          if (cgroups[k].Count == 0) {
285            cgroups.RemoveAt(k);
286            k--;
287          }
288        }
289        cgroups.Insert(0, new HashSet<int>(g));
290        child.Solution.SetGroups(cgroups);
291        if (changed) {
292          Evaluate(child, token);
293          if (bestChild == null || FitnessComparer.IsBetter(maximization, child.Fitness, bestChild.Fitness)) {
294            bestChild = (ISingleObjectiveSolutionScope<Encodings.LinearLinkageEncoding.LinearLinkage>)child.Clone();
295          }
296        }
297      };
298      return bestChild;
299    }
300  }
301}
Note: See TracBrowser for help on using the repository browser.