Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2701:

  • Added BinaryVectorEqualityComparer (identical to the one in the P3 plugin) to binaryvector plugin
  • Added delinking for absolute coded permutations
  • Some tweaks
File size: 11.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    [StorableConstructor]
41    protected BinaryMemPR(bool deserializing) : base(deserializing) { }
42    protected BinaryMemPR(BinaryMemPR original, Cloner cloner) : base(original, cloner) { }
43    public BinaryMemPR() {
44      foreach (var trainer in ApplicationManager.Manager.GetInstances<ISolutionModelTrainer<BinaryMemPRPopulationContext>>())
45        SolutionModelTrainerParameter.ValidValues.Add(trainer);
46     
47      foreach (var localSearch in ApplicationManager.Manager.GetInstances<ILocalSearch<BinaryMemPRSolutionContext>>()) {
48        LocalSearchParameter.ValidValues.Add(localSearch);
49      }
50    }
51
52    public override IDeepCloneable Clone(Cloner cloner) {
53      return new BinaryMemPR(this, cloner);
54    }
55
56    protected override bool Eq(BinaryVector a, BinaryVector b) {
57      var len = a.Length;
58      for (var i = 0; i < len; i++)
59        if (a[i] != b[i]) return false;
60      return true;
61    }
62
63    protected override double Dist(ISingleObjectiveSolutionScope<BinaryVector> a, ISingleObjectiveSolutionScope<BinaryVector> b) {
64      return 1.0 - HammingSimilarityCalculator.CalculateSimilarity(a.Solution, b.Solution);
65    }
66
67    protected override ISingleObjectiveSolutionScope<BinaryVector> ToScope(BinaryVector code, double fitness = double.NaN) {
68      var creator = Problem.SolutionCreator as IBinaryVectorCreator;
69      if (creator == null) throw new InvalidOperationException("Can only solve binary encoded problems with MemPR (binary)");
70      return new SingleObjectiveSolutionScope<BinaryVector>(code, creator.BinaryVectorParameter.ActualName, fitness, Problem.Evaluator.QualityParameter.ActualName) {
71        Parent = Context.Scope
72      };
73    }
74
75    protected override ISolutionSubspace<BinaryVector> CalculateSubspace(IEnumerable<BinaryVector> solutions, bool inverse = false) {
76      var pop = solutions.ToList();
77      var N = pop[0].Length;
78      var subspace = new bool[N];
79      for (var i = 0; i < N; i++) {
80        var val = pop[0][i];
81        if (inverse) subspace[i] = true;
82        for (var p = 1; p < pop.Count; p++) {
83          if (pop[p][i] != val) subspace[i] = !inverse;
84        }
85      }
86      return new BinarySolutionSubspace(subspace);
87    }
88
89    protected override void AdaptiveWalk(ISingleObjectiveSolutionScope<BinaryVector> scope, int maxEvals, CancellationToken token, ISolutionSubspace<BinaryVector> subspace = null) {
90      var evaluations = 0;
91      var subset = subspace != null ? ((BinarySolutionSubspace)subspace).Subspace : null;
92      if (double.IsNaN(scope.Fitness)) {
93        Evaluate(scope, token);
94        evaluations++;
95      }
96      SingleObjectiveSolutionScope<BinaryVector> bestOfTheWalk = null;
97      var currentScope = (SingleObjectiveSolutionScope<BinaryVector>)scope.Clone();
98      var current = currentScope.Solution;
99      var N = current.Length;
100
101      var subN = subset != null ? subset.Count(x => x) : N;
102      if (subN == 0) return;
103      var order = Enumerable.Range(0, N).Where(x => subset == null || subset[x]).Shuffle(Context.Random).ToArray();
104
105      var bound = Problem.Maximization ? Context.Population.Max(x => x.Fitness) : Context.Population.Min(x => x.Fitness);
106      var range = Math.Abs(bound - Context.LocalOptimaLevel);
107      if (range.IsAlmost(0)) range = Math.Abs(bound * 0.05);
108      if (range.IsAlmost(0)) { // because bound = localoptimalevel = 0
109        Context.IncrementEvaluatedSolutions(evaluations);
110        return;
111      }
112     
113      var temp = -range / Math.Log(1.0 / maxEvals);
114      var endtemp = -range / Math.Log(0.1 / maxEvals);
115      var annealFactor = Math.Pow(endtemp / temp, 1.0 / maxEvals);
116      for (var iter = 0; iter < int.MaxValue; iter++) {
117        var moved = false;
118
119        for (var i = 0; i < subN; i++) {
120          var idx = order[i];
121          var before = currentScope.Fitness;
122          current[idx] = !current[idx];
123          Evaluate(currentScope, token);
124          evaluations++;
125          var after = currentScope.Fitness;
126
127          if (Context.IsBetter(after, before) && (bestOfTheWalk == null || Context.IsBetter(after, bestOfTheWalk.Fitness))) {
128            bestOfTheWalk = (SingleObjectiveSolutionScope<BinaryVector>)currentScope.Clone();
129            if (Context.IsBetter(bestOfTheWalk, scope)) {
130              moved = false;
131              break;
132            }
133          }
134          var diff = Problem.Maximization ? after - before : before - after;
135          if (diff > 0) moved = true;
136          else {
137            var prob = Math.Exp(diff / temp);
138            if (Context.Random.NextDouble() >= prob) {
139              // the move is not good enough -> undo the move
140              current[idx] = !current[idx];
141              currentScope.Fitness = before;
142            }
143          }
144          temp *= annealFactor;
145          if (evaluations >= maxEvals) break;
146        }
147        if (!moved) break;
148        if (evaluations >= maxEvals) break;
149      }
150
151      Context.IncrementEvaluatedSolutions(evaluations);
152      scope.Adopt(bestOfTheWalk ?? currentScope);
153    }
154
155    protected override ISingleObjectiveSolutionScope<BinaryVector> Breed(ISingleObjectiveSolutionScope<BinaryVector> p1, ISingleObjectiveSolutionScope<BinaryVector> p2, CancellationToken token) {
156      var evaluations = 0;
157      var N = p1.Solution.Length;
158      if (double.IsNaN(p1.Fitness)) {
159        Evaluate(p1, token);
160        evaluations++;
161      }
162      if (double.IsNaN(p2.Fitness)) {
163        Evaluate(p2, token);
164        evaluations++;
165      }
166      var better = Problem.Maximization ? Math.Max(p1.Fitness, p2.Fitness)
167                                        : Math.Min(p1.Fitness, p2.Fitness);
168
169
170      var cache = new HashSet<BinaryVector>(new BinaryVectorEqualityComparer());
171      cache.Add(p1.Solution);
172      cache.Add(p2.Solution);
173
174      ISingleObjectiveSolutionScope<BinaryVector> offspring = null;
175      var probe = ToScope(new BinaryVector(N));
176      // first try all possible combinations of 1-point crossover
177      /*var order = Enumerable.Range(1, N - 2).Where(x => p1.Solution[x] != p2.Solution[x]).Shuffle(Context.Random).ToList();
178      foreach (var b in order) {
179        for (var i = 0; i <= b; i++)
180          probe.Solution[i] = p1.Solution[i];
181        for (var i = b + 1; i < probe.Solution.Length; i++)
182          probe.Solution[i] = p2.Solution[i];
183
184        // only add to cache, because all solutions must be unique
185        if (cache.Contains(probe.Solution)) continue;
186        cache.Add(probe.Solution);
187        Evaluate(probe, token);
188        evaluations++;
189        if (offspring == null || Context.IsBetter(probe, offspring)) {
190          // immediately return upon finding a better offspring than better parent
191          if (Context.IsBetter(probe.Fitness, better)) {
192            Context.IncrementEvaluatedSolutions(evaluations);
193            return probe;
194          }
195          offspring = (ISingleObjectiveSolutionScope<BinaryVector>)probe.Clone();
196        }
197      }*/
198
199      var cacheHits = 0;
200      // if we got some evaluations left, try uniform crossover
201      while (evaluations < Math.Min(Context.LocalSearchEvaluations, N)) {
202        probe.Solution = UniformCrossover.Apply(Context.Random, p1.Solution, p2.Solution);
203        if (cache.Contains(probe.Solution)) {
204          cacheHits++;
205          if (cacheHits > 10) break; // variability of uniform crossover is too low -> parents are too similar
206          continue;
207        } else cache.Add(probe.Solution);
208        Evaluate(probe, token);
209        evaluations++;
210        if (offspring == null || Context.IsBetter(probe, offspring)) {
211          // immediately return upon finding a better offspring than better parent
212          if (Context.IsBetter(probe.Fitness, better)) {
213            Context.IncrementEvaluatedSolutions(evaluations);
214            return probe;
215          }
216          offspring = (ISingleObjectiveSolutionScope<BinaryVector>)probe.Clone();
217        }
218      }
219      Context.IncrementEvaluatedSolutions(evaluations);
220      // return best offspring found
221      return offspring ?? probe;
222    }
223
224    protected override ISingleObjectiveSolutionScope<BinaryVector> Link(ISingleObjectiveSolutionScope<BinaryVector> a, ISingleObjectiveSolutionScope<BinaryVector> b, CancellationToken token, bool delink = false) {
225      var evaluations = 0;
226      if (double.IsNaN(a.Fitness)) {
227        Evaluate(a, token);
228        evaluations++;
229      }
230      if (double.IsNaN(b.Fitness)) {
231        Evaluate(b, token);
232        evaluations++;
233      }
234
235      var childScope = (ISingleObjectiveSolutionScope<BinaryVector>)a.Clone();
236      var child = childScope.Solution;
237      ISingleObjectiveSolutionScope<BinaryVector> best = null;
238      var cF = a.Fitness;
239      var bF = double.NaN;
240      var order = Enumerable.Range(0, child.Length)
241        .Where(x => !delink && child[x] != b.Solution[x] || delink && child[x] == b.Solution[x])
242        .Shuffle(Context.Random).ToList();
243      if (order.Count == 0) return childScope;
244
245      while (true) {
246        var bestS = double.NaN;
247        var bestI = -1;
248        for (var i = 0; i < order.Count; i++) {
249          var idx = order[i];
250          child[idx] = !child[idx]; // move
251          Evaluate(childScope, token);
252          evaluations++;
253          var s = childScope.Fitness;
254          childScope.Fitness = cF;
255          child[idx] = !child[idx]; // undo move
256          if (Context.IsBetter(s, cF)) {
257            bestS = s;
258            bestI = i;
259            break; // first-improvement
260          }
261          if (Context.IsBetter(s, bestS)) {
262            // least-degrading
263            bestS = s;
264            bestI = i;
265          }
266        }
267        child[order[bestI]] = !child[order[bestI]];
268        order.RemoveAt(bestI);
269        cF = bestS;
270        childScope.Fitness = cF;
271        if (Context.IsBetter(cF, bF)) {
272          bF = cF;
273          best = (ISingleObjectiveSolutionScope<BinaryVector>)childScope.Clone();
274        }
275        if (order.Count == 0) break;
276      }
277      Context.IncrementEvaluatedSolutions(evaluations);
278      return best ?? childScope;
279    }
280  }
281}
Note: See TracBrowser for help on using the repository browser.