Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2701:

  • Added alternating bits binary test Problem
  • Refactored MemPR to work with programmable problem in current trunk
  • fixed a bug in permutation MemPR when crossover doesn't assign an offspring
File size: 13.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 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;
34
35namespace HeuristicLab.Algorithms.MemPR.Grouping {
36  [Item("MemPR (linear linkage)", "MemPR implementation for linear linkage vectors.")]
37  [StorableClass]
38  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 999)]
39  public class LinearLinkageMemPR : MemPRAlgorithm<ISingleObjectiveHeuristicOptimizationProblem, LinearLinkage, LinearLinkageMemPRPopulationContext, LinearLinkageMemPRSolutionContext> {
40    [StorableConstructor]
41    protected LinearLinkageMemPR(bool deserializing) : base(deserializing) { }
42    protected LinearLinkageMemPR(LinearLinkageMemPR original, Cloner cloner) : base(original, cloner) { }
43    public LinearLinkageMemPR() {
44      foreach (var trainer in ApplicationManager.Manager.GetInstances<ISolutionModelTrainer<LinearLinkageMemPRPopulationContext>>())
45        SolutionModelTrainerParameter.ValidValues.Add(trainer);
46     
47      foreach (var localSearch in ApplicationManager.Manager.GetInstances<ILocalSearch<LinearLinkageMemPRSolutionContext>>()) {
48        LocalSearchParameter.ValidValues.Add(localSearch);
49      }
50    }
51
52    public override IDeepCloneable Clone(Cloner cloner) {
53      return new LinearLinkageMemPR(this, cloner);
54    }
55
56    protected override bool Eq(LinearLinkage a, LinearLinkage b) {
57      if (a.Length != b.Length) return false;
58      for (var i = 0; i < a.Length; i++)
59        if (a[i] != b[i]) return false;
60      return true;
61    }
62
63    protected override double Dist(ISingleObjectiveSolutionScope<LinearLinkage> a, ISingleObjectiveSolutionScope<LinearLinkage> b) {
64      return Dist(a.Solution, b.Solution);
65    }
66
67    private double Dist(LinearLinkage a, LinearLinkage b) {
68      return 1.0 - HammingSimilarityCalculator.CalculateSimilarity(a, b);
69    }
70
71    protected override ISolutionSubspace<LinearLinkage> CalculateSubspace(IEnumerable<LinearLinkage> solutions, bool inverse = false) {
72      var pop = solutions.ToList();
73      var N = pop[0].Length;
74      var subspace = new bool[N];
75      for (var i = 0; i < N; i++) {
76        var val = pop[0][i];
77        if (inverse) subspace[i] = true;
78        for (var p = 1; p < pop.Count; p++) {
79          if (pop[p][i] != val) subspace[i] = !inverse;
80        }
81      }
82      return new LinearLinkageSolutionSubspace(subspace);
83    }
84
85    protected override void AdaptiveWalk(
86        ISingleObjectiveSolutionScope<LinearLinkage> scope,
87        int maxEvals, CancellationToken token,
88        ISolutionSubspace<LinearLinkage> sub_space = null) {
89      var maximization = Context.Maximization;
90      var subspace = sub_space is LinearLinkageSolutionSubspace ? ((LinearLinkageSolutionSubspace)sub_space).Subspace : null;
91      var evaluations = 0;
92      var quality = scope.Fitness;
93      if (double.IsNaN(quality)) {
94        Context.Evaluate(scope, token);
95        quality = scope.Fitness;
96        evaluations++;
97        if (evaluations >= maxEvals) return;
98      }
99      var bestQuality = quality;
100      var currentScope = (ISingleObjectiveSolutionScope<LinearLinkage>)scope.Clone();
101      var current = currentScope.Solution;
102      LinearLinkage bestOfTheWalk = null;
103      var bestOfTheWalkF = double.NaN;
104
105      var tabu = new double[current.Length, current.Length];
106      for (var i = 0; i < current.Length; i++) {
107        for (var j = i; j < current.Length; j++) {
108          tabu[i, j] = tabu[j, i] = maximization ? double.MinValue : double.MaxValue;
109        }
110        tabu[i, current[i]] = quality;
111      }
112
113      // this dictionary holds the last relevant links
114      var groupItems = new List<int>();
115      var lleb = current.ToBackLinks();
116      Move bestOfTheRest = null;
117      var bestOfTheRestF = double.NaN;
118      var lastAppliedMove = -1;
119      for (var iter = 0; iter < int.MaxValue; iter++) {
120        // clear the dictionary before a new pass through the array is made
121        groupItems.Clear();
122        for (var i = 0; i < current.Length; i++) {
123          if (subspace != null && !subspace[i]) {
124            if (lleb[i] != i)
125              groupItems.Remove(lleb[i]);
126            groupItems.Add(i);
127            continue;
128          }
129
130          var next = current[i];
131
132          if (lastAppliedMove == i) {
133            if (bestOfTheRest != null) {
134              bestOfTheRest.Apply(current);
135              bestOfTheRest.ApplyToLLEb(lleb);
136              currentScope.Fitness = bestOfTheRestF;
137              quality = bestOfTheRestF;
138              if (maximization) {
139                tabu[i, next] = Math.Max(tabu[i, next], bestOfTheRestF);
140                tabu[i, current[i]] = Math.Max(tabu[i, current[i]], bestOfTheRestF);
141              } else {
142                tabu[i, next] = Math.Min(tabu[i, next], bestOfTheRestF);
143                tabu[i, current[i]] = Math.Min(tabu[i, current[i]], bestOfTheRestF);
144              }
145              if (FitnessComparer.IsBetter(maximization, bestOfTheRestF, bestOfTheWalkF)) {
146                bestOfTheWalk = (LinearLinkage)current.Clone();
147                bestOfTheWalkF = bestOfTheRestF;
148              }
149              bestOfTheRest = null;
150              bestOfTheRestF = double.NaN;
151              lastAppliedMove = i;
152            } else {
153              lastAppliedMove = -1;
154            }
155            break;
156          } else {
157            foreach (var move in MoveGenerator.GenerateForItem(i, groupItems, current, lleb)) {
158              // we intend to break link i -> next
159              var qualityToBreak = tabu[i, next];
160              move.Apply(current);
161              var qualityToRestore = tabu[i, current[i]]; // current[i] is new next
162              Context.Evaluate(currentScope, token);
163              evaluations++;
164              var moveF = currentScope.Fitness;
165              var isNotTabu = FitnessComparer.IsBetter(maximization, moveF, qualityToBreak)
166                              && FitnessComparer.IsBetter(maximization, moveF, qualityToRestore);
167              var isImprovement = FitnessComparer.IsBetter(maximization, moveF, quality);
168              var isAspired = FitnessComparer.IsBetter(maximization, moveF, bestQuality);
169              if ((isNotTabu && isImprovement) || isAspired) {
170                if (maximization) {
171                  tabu[i, next] = Math.Max(tabu[i, next], moveF);
172                  tabu[i, current[i]] = Math.Max(tabu[i, current[i]], moveF);
173                } else {
174                  tabu[i, next] = Math.Min(tabu[i, next], moveF);
175                  tabu[i, current[i]] = Math.Min(tabu[i, current[i]], moveF);
176                }
177                quality = moveF;
178                if (isAspired) bestQuality = quality;
179
180                move.ApplyToLLEb(lleb);
181
182                if (FitnessComparer.IsBetter(maximization, moveF, bestOfTheWalkF)) {
183                  bestOfTheWalk = (LinearLinkage)current.Clone();
184                  bestOfTheWalkF = moveF;
185                }
186
187                bestOfTheRest = null;
188                bestOfTheRestF = double.NaN;
189                lastAppliedMove = i;
190                break;
191              } else {
192                if (isNotTabu) {
193                  if (FitnessComparer.IsBetter(maximization, moveF, bestOfTheRestF)) {
194                    bestOfTheRest = move;
195                    bestOfTheRestF = moveF;
196                  }
197                }
198                move.Undo(current);
199                currentScope.Fitness = quality;
200              }
201              if (evaluations >= maxEvals) break;
202            }
203          }
204          if (lleb[i] != i)
205            groupItems.Remove(lleb[i]);
206          groupItems.Add(i);
207          if (evaluations >= maxEvals) break;
208          if (token.IsCancellationRequested) break;
209        }
210        if (lastAppliedMove == -1) { // no move has been applied
211          if (bestOfTheRest != null) {
212            var i = bestOfTheRest.Item;
213            var next = current[i];
214            bestOfTheRest.Apply(current);
215            currentScope.Fitness = bestOfTheRestF;
216            quality = bestOfTheRestF;
217            if (maximization) {
218              tabu[i, next] = Math.Max(tabu[i, next], bestOfTheRestF);
219              tabu[i, current[i]] = Math.Max(tabu[i, current[i]], bestOfTheRestF);
220            } else {
221              tabu[i, next] = Math.Min(tabu[i, next], bestOfTheRestF);
222              tabu[i, current[i]] = Math.Min(tabu[i, current[i]], bestOfTheRestF);
223            }
224            if (FitnessComparer.IsBetter(maximization, bestOfTheRestF, bestOfTheWalkF)) {
225              bestOfTheWalk = (LinearLinkage)current.Clone();
226              bestOfTheWalkF = bestOfTheRestF;
227            }
228
229            bestOfTheRest = null;
230            bestOfTheRestF = double.NaN;
231          } else break;
232        }
233        if (evaluations >= maxEvals) break;
234        if (token.IsCancellationRequested) break;
235      }
236      if (bestOfTheWalk != null) {
237        scope.Solution = bestOfTheWalk;
238        scope.Fitness = bestOfTheWalkF;
239      }
240    }
241
242    protected override ISingleObjectiveSolutionScope<LinearLinkage> Breed(ISingleObjectiveSolutionScope<LinearLinkage> p1, ISingleObjectiveSolutionScope<LinearLinkage> p2, CancellationToken token) {
243      var cache = new HashSet<LinearLinkage>(new LinearLinkageEqualityComparer());
244      cache.Add(p1.Solution);
245      cache.Add(p2.Solution);
246
247      var cachehits = 0;
248      var evaluations = 0;
249      var probe = Context.ToScope((LinearLinkage)p1.Solution.Clone());
250      ISingleObjectiveSolutionScope<LinearLinkage> offspring = null;
251      while (evaluations < p1.Solution.Length) {
252        LinearLinkage c = null;
253        if (Context.Random.NextDouble() < 0.8)
254          c = GroupCrossover.Apply(Context.Random, p1.Solution, p2.Solution);
255        else c = SinglePointCrossover.Apply(Context.Random, p1.Solution, p2.Solution);
256       
257        if (cache.Contains(c)) {
258          cachehits++;
259          if (cachehits > 10) break;
260          continue;
261        }
262        Context.Evaluate(probe, token);
263        evaluations++;
264        cache.Add(c);
265        if (offspring == null || Context.IsBetter(probe, offspring)) {
266          offspring = probe;
267          if (Context.IsBetter(offspring, p1) && Context.IsBetter(offspring, p2))
268            break;
269        }
270      }
271      Context.IncrementEvaluatedSolutions(evaluations);
272      return offspring ?? probe;
273    }
274
275    protected override ISingleObjectiveSolutionScope<LinearLinkage> Link(ISingleObjectiveSolutionScope<LinearLinkage> a, ISingleObjectiveSolutionScope<LinearLinkage> b, CancellationToken token, bool delink = false) {
276      var evaluations = 0;
277      var probe = (ISingleObjectiveSolutionScope<LinearLinkage>)a.Clone();
278      ISingleObjectiveSolutionScope<LinearLinkage> best = null;
279      while (true) {
280        Move bestMove = null;
281        var bestMoveQ = double.NaN;
282        // this approach may not fully relink the two solutions
283        foreach (var m in MoveGenerator.Generate(probe.Solution)) {
284          var distBefore = Dist(probe, b);
285          m.Apply(probe.Solution);
286          var distAfter = Dist(probe, b);
287          // consider all moves that would increase the distance between probe and b
288          // or decrease it depending on whether we do delinking or relinking
289          if (delink && distAfter > distBefore || !delink && distAfter < distBefore) {
290            var beforeQ = probe.Fitness;
291            Context.Evaluate(probe, token);
292            evaluations++;
293            var q = probe.Fitness;
294            m.Undo(probe.Solution);
295            probe.Fitness = beforeQ;
296
297            if (Context.IsBetter(q, bestMoveQ)) {
298              bestMove = m;
299              bestMoveQ = q;
300            }
301            if (Context.IsBetter(q, beforeQ)) break;
302          } else m.Undo(probe.Solution);
303        }
304        if (bestMove == null) break;
305        bestMove.Apply(probe.Solution);
306        probe.Fitness = bestMoveQ;
307        if (best == null || Context.IsBetter(probe, best))
308          best = (ISingleObjectiveSolutionScope<LinearLinkage>)probe.Clone();
309      }
310      Context.IncrementEvaluatedSolutions(evaluations);
311
312      return best ?? probe;
313    }
314  }
315}
Note: See TracBrowser for help on using the repository browser.