Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2701: working on MemPR implementation

File size: 10.7 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 subset = subspace != null ? ((BinarySolutionSubspace)subspace).Subspace : null;
101      if (double.IsNaN(scope.Fitness)) Evaluate(scope, token);
102      SingleObjectiveSolutionScope<BinaryVector> bestOfTheWalk = null;
103      var currentScope = (SingleObjectiveSolutionScope<BinaryVector>)scope.Clone();
104      var current = currentScope.Solution;
105      var N = current.Length;
106      var tabu = new Tuple<double, double>[N];
107      for (var i = 0; i < N; i++) tabu[i] = Tuple.Create(current[i] ? double.NaN : currentScope.Fitness, !current[i] ? double.NaN : currentScope.Fitness);
108      var subN = subset != null ? subset.Count(x => x) : N;
109      if (subN == 0) return;
110      var order = Enumerable.Range(0, N).Where(x => subset == null || subset[x]).Shuffle(Context.Random).ToArray();
111
112      for (var iter = 0; iter < steps; iter++) {
113        var allTabu = true;
114        var bestOfTheRestF = double.NaN;
115        int bestOfTheRest = -1;
116        var improved = false;
117
118        for (var i = 0; i < subN; i++) {
119          var idx = order[i];
120          var before = currentScope.Fitness;
121          current[idx] = !current[idx];
122          Evaluate(currentScope, token);
123          var after = currentScope.Fitness;
124
125          if (IsBetter(after, before) && (bestOfTheWalk == null || IsBetter(after, bestOfTheWalk.Fitness))) {
126            bestOfTheWalk = (SingleObjectiveSolutionScope<BinaryVector>)currentScope.Clone();
127          }
128
129          var qualityToBeat = current[idx] ? tabu[idx].Item2 : tabu[idx].Item1;
130          var isTabu = !IsBetter(after, qualityToBeat);
131          if (!isTabu) allTabu = false;
132
133          if (IsBetter(after, before) && !isTabu) {
134            improved = true;
135            tabu[idx] = current[idx] ? Tuple.Create(after, tabu[idx].Item2) : Tuple.Create(tabu[idx].Item1, after);
136          } else { // undo the move
137            if (!isTabu && IsBetter(after, bestOfTheRestF)) {
138              bestOfTheRest = idx;
139              bestOfTheRestF = after;
140            }
141            current[idx] = !current[idx];
142            currentScope.Fitness = before;
143          }
144        }
145        if (!allTabu && !improved) {
146          var better = currentScope.Fitness;
147          current[bestOfTheRest] = !current[bestOfTheRest];
148          tabu[bestOfTheRest] = current[bestOfTheRest] ? Tuple.Create(better, tabu[bestOfTheRest].Item2) : Tuple.Create(tabu[bestOfTheRest].Item1, better);
149          currentScope.Fitness = bestOfTheRestF;
150        } else if (allTabu) break;
151      }
152
153      scope.Adopt(bestOfTheWalk ?? currentScope);
154    }
155
156    protected override ISingleObjectiveSolutionScope<BinaryVector> Cross(ISingleObjectiveSolutionScope<BinaryVector> p1, ISingleObjectiveSolutionScope<BinaryVector> p2, CancellationToken token) {
157      var offspring = (ISingleObjectiveSolutionScope<BinaryVector>)p1.Clone();
158      offspring.Fitness = double.NaN;
159      var code = offspring.Solution;
160      var p2Code = p2.Solution;
161      var bp = 0;
162      var lastbp = 0;
163      for (var i = 0; i < code.Length; i++) {
164        if (bp % 2 == 1) {
165          code[i] = p2Code[i];
166        }
167        if (Context.Random.Next(code.Length) < i - lastbp + 1) {
168          bp = (bp + 1) % 2;
169          lastbp = i;
170        }
171      }
172      return offspring;
173    }
174
175    protected override void Mutate(ISingleObjectiveSolutionScope<BinaryVector> offspring, CancellationToken token, ISolutionSubspace<BinaryVector> subspace = null) {
176      var subset = subspace != null ? ((BinarySolutionSubspace)subspace).Subspace : null;
177      offspring.Fitness = double.NaN;
178      var code = offspring.Solution;
179      for (var i = 0; i < code.Length; i++) {
180        if (subset != null && subset[i]) continue;
181        if (Context.Random.NextDouble() < UncommonBitSubsetMutationProbabilityMagicConst) {
182          code[i] = !code[i];
183          if (subset != null) subset[i] = true;
184        }
185      }
186    }
187
188    protected override ISingleObjectiveSolutionScope<BinaryVector> Relink(ISingleObjectiveSolutionScope<BinaryVector> a, ISingleObjectiveSolutionScope<BinaryVector> b, CancellationToken token) {
189      if (double.IsNaN(a.Fitness)) Evaluate(a, token);
190      if (double.IsNaN(b.Fitness)) Evaluate(b, token);
191      if (Context.Random.NextDouble() < 0.5)
192        return IsBetter(a, b) ? Relink(a, b, token, false) : Relink(b, a, token, true);
193      else return IsBetter(a, b) ? Relink(b, a, token, true) : Relink(a, b, token, false);
194    }
195
196    protected virtual ISingleObjectiveSolutionScope<BinaryVector> Relink(ISingleObjectiveSolutionScope<BinaryVector> betterScope, ISingleObjectiveSolutionScope<BinaryVector> worseScope, CancellationToken token, bool fromWorseToBetter) {
197      var childScope = (ISingleObjectiveSolutionScope<BinaryVector>)(fromWorseToBetter ? worseScope : betterScope).Clone();
198      var child = childScope.Solution;
199      var better = betterScope.Solution;
200      var worse = worseScope.Solution;
201      ISingleObjectiveSolutionScope<BinaryVector> best = null;
202      var cF = fromWorseToBetter ? worseScope.Fitness : betterScope.Fitness;
203      var bF = double.NaN;
204      var order = Enumerable.Range(0, better.Length).Shuffle(Context.Random).ToArray();
205      while (true) {
206        var bestS = double.NaN;
207        var bestIdx = -1;
208        for (var i = 0; i < child.Length; i++) {
209          var idx = order[i];
210          // either move from worse to better or move from better away from worse
211          if (fromWorseToBetter && child[idx] == better[idx] ||
212            !fromWorseToBetter && child[idx] != worse[idx]) continue;
213          child[idx] = !child[idx]; // move
214          Evaluate(childScope, token);
215          var s = childScope.Fitness;
216          childScope.Fitness = cF;
217          child[idx] = !child[idx]; // undo move
218          if (IsBetter(s, cF)) {
219            bestS = s;
220            bestIdx = idx;
221            break; // first-improvement
222          }
223          if (double.IsNaN(bestS) || IsBetter(s, bestS)) {
224            // least-degrading
225            bestS = s;
226            bestIdx = idx;
227          }
228        }
229        if (bestIdx < 0) break;
230        child[bestIdx] = !child[bestIdx];
231        cF = bestS;
232        childScope.Fitness = cF;
233        if (IsBetter(cF, bF)) {
234          bF = cF;
235          best = (ISingleObjectiveSolutionScope<BinaryVector>)childScope.Clone();
236        }
237      }
238      return best ?? childScope;
239    }
240  }
241}
Note: See TracBrowser for help on using the repository browser.