Free cookie consent management tool by TermsFeed Policy Generator

source: branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/Binary/BinaryMemPR.cs @ 14453

Last change on this file since 14453 was 14453, checked in by abeham, 7 years ago

#2701:

  • Worked on MemPR algorithm for permutations
    • Made Evaluate() method mostly thread-safe and moved evaluated solutions counting to caller
  • Removed TSP specific similarity calculator (it is actually not specific to the TSP) and added it to the permutation encoding as HammingSimilarityCalculator
  • Fixed bug in qap basicproblem
File size: 11.1 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.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Encodings.BinaryVectorEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.PluginInfrastructure;
33using HeuristicLab.Random;
34
35namespace HeuristicLab.Algorithms.MemPR.Binary {
36  [Item("MemPR (binary)", "MemPR implementation for binary vectors.")]
37  [StorableClass]
38  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 999)]
39  public class BinaryMemPR : MemPRAlgorithm<SingleObjectiveBasicProblem<BinaryVectorEncoding>, BinaryVector, BinaryMemPRPopulationContext, BinaryMemPRSolutionContext> {
40    private const double UncommonBitSubsetMutationProbabilityMagicConst = 0.05;
41   
42    [StorableConstructor]
43    protected BinaryMemPR(bool deserializing) : base(deserializing) { }
44    protected BinaryMemPR(BinaryMemPR original, Cloner cloner) : base(original, cloner) { }
45    public BinaryMemPR() {
46      foreach (var trainer in ApplicationManager.Manager.GetInstances<ISolutionModelTrainer<BinaryMemPRPopulationContext>>())
47        SolutionModelTrainerParameter.ValidValues.Add(trainer);
48     
49      foreach (var localSearch in ApplicationManager.Manager.GetInstances<ILocalSearch<BinaryMemPRSolutionContext>>()) {
50        LocalSearchParameter.ValidValues.Add(localSearch);
51      }
52    }
53
54    public override IDeepCloneable Clone(Cloner cloner) {
55      return new BinaryMemPR(this, cloner);
56    }
57
58    protected override bool Eq(ISingleObjectiveSolutionScope<BinaryVector> a, ISingleObjectiveSolutionScope<BinaryVector> b) {
59      var len = a.Solution.Length;
60      var acode = a.Solution;
61      var bcode = b.Solution;
62      for (var i = 0; i < len; i++)
63        if (acode[i] != bcode[i]) return false;
64      return true;
65    }
66
67    protected override double Dist(ISingleObjectiveSolutionScope<BinaryVector> a, ISingleObjectiveSolutionScope<BinaryVector> b) {
68      var len = a.Solution.Length;
69      var acode = a.Solution;
70      var bcode = b.Solution;
71      var hamming = 0;
72      for (var i = 0; i < len; i++)
73        if (acode[i] != bcode[i]) hamming++;
74      return hamming / (double)len;
75    }
76
77    protected override ISingleObjectiveSolutionScope<BinaryVector> ToScope(BinaryVector code, double fitness = double.NaN) {
78      var creator = Problem.SolutionCreator as IBinaryVectorCreator;
79      if (creator == null) throw new InvalidOperationException("Can only solve binary encoded problems with MemPR (binary)");
80      return new SingleObjectiveSolutionScope<BinaryVector>(code, creator.BinaryVectorParameter.ActualName, fitness, Problem.Evaluator.QualityParameter.ActualName) {
81        Parent = Context.Scope
82      };
83    }
84
85    protected override ISolutionSubspace<BinaryVector> CalculateSubspace(IEnumerable<BinaryVector> solutions, bool inverse = false) {
86      var pop = solutions.ToList();
87      var N = pop[0].Length;
88      var subspace = new bool[N];
89      for (var i = 0; i < N; i++) {
90        var val = pop[0][i];
91        if (inverse) subspace[i] = true;
92        for (var p = 1; p < pop.Count; p++) {
93          if (pop[p][i] != val) subspace[i] = !inverse;
94        }
95      }
96      return new BinarySolutionSubspace(subspace);
97    }
98
99    protected override void TabuWalk(ISingleObjectiveSolutionScope<BinaryVector> scope, int steps, CancellationToken token, ISolutionSubspace<BinaryVector> subspace = null) {
100      var evaluations = 0;
101      var subset = subspace != null ? ((BinarySolutionSubspace)subspace).Subspace : null;
102      if (double.IsNaN(scope.Fitness)) {
103        Evaluate(scope, token);
104        evaluations++;
105      }
106      SingleObjectiveSolutionScope<BinaryVector> bestOfTheWalk = null;
107      var currentScope = (SingleObjectiveSolutionScope<BinaryVector>)scope.Clone();
108      var current = currentScope.Solution;
109      var N = current.Length;
110      var tabu = new Tuple<double, double>[N];
111      for (var i = 0; i < N; i++) tabu[i] = Tuple.Create(current[i] ? double.NaN : currentScope.Fitness, !current[i] ? double.NaN : currentScope.Fitness);
112      var subN = subset != null ? subset.Count(x => x) : N;
113      if (subN == 0) return;
114      var order = Enumerable.Range(0, N).Where(x => subset == null || subset[x]).Shuffle(Context.Random).ToArray();
115
116      for (var iter = 0; iter < steps; iter++) {
117        var allTabu = true;
118        var bestOfTheRestF = double.NaN;
119        int bestOfTheRest = -1;
120        var improved = false;
121
122        for (var i = 0; i < subN; i++) {
123          var idx = order[i];
124          var before = currentScope.Fitness;
125          current[idx] = !current[idx];
126          Evaluate(currentScope, token);
127          evaluations++;
128          var after = currentScope.Fitness;
129
130          if (IsBetter(after, before) && (bestOfTheWalk == null || IsBetter(after, bestOfTheWalk.Fitness))) {
131            bestOfTheWalk = (SingleObjectiveSolutionScope<BinaryVector>)currentScope.Clone();
132          }
133
134          var qualityToBeat = current[idx] ? tabu[idx].Item2 : tabu[idx].Item1;
135          var isTabu = !IsBetter(after, qualityToBeat);
136          if (!isTabu) allTabu = false;
137
138          if (IsBetter(after, before) && !isTabu) {
139            improved = true;
140            tabu[idx] = current[idx] ? Tuple.Create(after, tabu[idx].Item2) : Tuple.Create(tabu[idx].Item1, after);
141          } else { // undo the move
142            if (!isTabu && IsBetter(after, bestOfTheRestF)) {
143              bestOfTheRest = idx;
144              bestOfTheRestF = after;
145            }
146            current[idx] = !current[idx];
147            currentScope.Fitness = before;
148          }
149        }
150        if (!allTabu && !improved) {
151          var better = currentScope.Fitness;
152          current[bestOfTheRest] = !current[bestOfTheRest];
153          tabu[bestOfTheRest] = current[bestOfTheRest] ? Tuple.Create(better, tabu[bestOfTheRest].Item2) : Tuple.Create(tabu[bestOfTheRest].Item1, better);
154          currentScope.Fitness = bestOfTheRestF;
155        } else if (allTabu) break;
156      }
157
158      Context.IncrementEvaluatedSolutions(evaluations);
159      scope.Adopt(bestOfTheWalk ?? currentScope);
160    }
161
162    protected override ISingleObjectiveSolutionScope<BinaryVector> Cross(ISingleObjectiveSolutionScope<BinaryVector> p1, ISingleObjectiveSolutionScope<BinaryVector> p2, CancellationToken token) {
163      var offspring = (ISingleObjectiveSolutionScope<BinaryVector>)p1.Clone();
164      offspring.Fitness = double.NaN;
165      var code = offspring.Solution;
166      var p2Code = p2.Solution;
167      var bp = 0;
168      var lastbp = 0;
169      for (var i = 0; i < code.Length; i++) {
170        if (bp % 2 == 1) {
171          code[i] = p2Code[i];
172        }
173        if (Context.Random.Next(code.Length) < i - lastbp + 1) {
174          bp = (bp + 1) % 2;
175          lastbp = i;
176        }
177      }
178      return offspring;
179    }
180
181    protected override void Mutate(ISingleObjectiveSolutionScope<BinaryVector> offspring, CancellationToken token, ISolutionSubspace<BinaryVector> subspace = null) {
182      var subset = subspace != null ? ((BinarySolutionSubspace)subspace).Subspace : null;
183      offspring.Fitness = double.NaN;
184      var code = offspring.Solution;
185      for (var i = 0; i < code.Length; i++) {
186        if (subset != null && subset[i]) continue;
187        if (Context.Random.NextDouble() < UncommonBitSubsetMutationProbabilityMagicConst) {
188          code[i] = !code[i];
189          if (subset != null) subset[i] = true;
190        }
191      }
192    }
193
194    protected override ISingleObjectiveSolutionScope<BinaryVector> Relink(ISingleObjectiveSolutionScope<BinaryVector> a, ISingleObjectiveSolutionScope<BinaryVector> b, CancellationToken token) {
195      if (double.IsNaN(a.Fitness)) {
196        Evaluate(a, token);
197        Context.IncrementEvaluatedSolutions(1);
198      }
199      if (double.IsNaN(b.Fitness)) {
200        Evaluate(b, token);
201        Context.IncrementEvaluatedSolutions(1);
202      }
203      if (Context.Random.NextDouble() < 0.5)
204        return IsBetter(a, b) ? Relink(a, b, token, false) : Relink(b, a, token, true);
205      else return IsBetter(a, b) ? Relink(b, a, token, true) : Relink(a, b, token, false);
206    }
207
208    protected virtual ISingleObjectiveSolutionScope<BinaryVector> Relink(ISingleObjectiveSolutionScope<BinaryVector> betterScope, ISingleObjectiveSolutionScope<BinaryVector> worseScope, CancellationToken token, bool fromWorseToBetter) {
209      var evaluations = 0;
210      var childScope = (ISingleObjectiveSolutionScope<BinaryVector>)(fromWorseToBetter ? worseScope : betterScope).Clone();
211      var child = childScope.Solution;
212      var better = betterScope.Solution;
213      var worse = worseScope.Solution;
214      ISingleObjectiveSolutionScope<BinaryVector> best = null;
215      var cF = fromWorseToBetter ? worseScope.Fitness : betterScope.Fitness;
216      var bF = double.NaN;
217      var order = Enumerable.Range(0, better.Length).Shuffle(Context.Random).ToArray();
218      while (true) {
219        var bestS = double.NaN;
220        var bestIdx = -1;
221        for (var i = 0; i < child.Length; i++) {
222          var idx = order[i];
223          // either move from worse to better or move from better away from worse
224          if (fromWorseToBetter && child[idx] == better[idx] ||
225            !fromWorseToBetter && child[idx] != worse[idx]) continue;
226          child[idx] = !child[idx]; // move
227          Evaluate(childScope, token);
228          evaluations++;
229          var s = childScope.Fitness;
230          childScope.Fitness = cF;
231          child[idx] = !child[idx]; // undo move
232          if (IsBetter(s, cF)) {
233            bestS = s;
234            bestIdx = idx;
235            break; // first-improvement
236          }
237          if (double.IsNaN(bestS) || IsBetter(s, bestS)) {
238            // least-degrading
239            bestS = s;
240            bestIdx = idx;
241          }
242        }
243        if (bestIdx < 0) break;
244        child[bestIdx] = !child[bestIdx];
245        cF = bestS;
246        childScope.Fitness = cF;
247        if (IsBetter(cF, bF)) {
248          bF = cF;
249          best = (ISingleObjectiveSolutionScope<BinaryVector>)childScope.Clone();
250        }
251      }
252      Context.IncrementEvaluatedSolutions(evaluations);
253      return best ?? childScope;
254    }
255  }
256}
Note: See TracBrowser for help on using the repository browser.