Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2708: added binary version of mempr with new concepts of scope in basic alg

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