Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2701: refactored breeding, removed hillclimbing after breeding

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