Free cookie consent management tool by TermsFeed Policy Generator

source: branches/MemPRAlgorithm/HeuristicLab.Algorithms.MemPR/3.3/MemPRAlgorithm.cs @ 14466

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

#2701:

  • Using evaluated solutions from HC as max evaluations for tabu walking in MemPR
  • Fixed some bugs in MemPR (permutation) regarding subspace calculation (true means okay, false means no)
  • Fixed bug in TSP
File size: 33.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.ComponentModel;
25using System.Linq;
26using System.Runtime.CompilerServices;
27using System.Threading;
28using HeuristicLab.Algorithms.MemPR.Interfaces;
29using HeuristicLab.Algorithms.MemPR.Util;
30using HeuristicLab.Analysis;
31using HeuristicLab.Common;
32using HeuristicLab.Core;
33using HeuristicLab.Data;
34using HeuristicLab.Optimization;
35using HeuristicLab.Parameters;
36using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
37
38namespace HeuristicLab.Algorithms.MemPR {
39  [Item("MemPR Algorithm", "Base class for MemPR algorithms")]
40  [StorableClass]
41  public abstract class MemPRAlgorithm<TProblem, TSolution, TPopulationContext, TSolutionContext> : BasicAlgorithm, INotifyPropertyChanged
42      where TProblem : class, IItem, ISingleObjectiveHeuristicOptimizationProblem, ISingleObjectiveProblemDefinition
43      where TSolution : class, IItem
44      where TPopulationContext : MemPRPopulationContext<TProblem, TSolution, TPopulationContext, TSolutionContext>, new()
45      where TSolutionContext : MemPRSolutionContext<TProblem, TSolution, TPopulationContext, TSolutionContext> {
46    private const double MutationProbabilityMagicConst = 0.1;
47
48    public override Type ProblemType {
49      get { return typeof(TProblem); }
50    }
51
52    public new TProblem Problem {
53      get { return (TProblem)base.Problem; }
54      set { base.Problem = value; }
55    }
56
57    protected string QualityName {
58      get { return Problem != null && Problem.Evaluator != null ? Problem.Evaluator.QualityParameter.ActualName : null; }
59    }
60
61    public int? MaximumEvaluations {
62      get {
63        var val = ((OptionalValueParameter<IntValue>)Parameters["MaximumEvaluations"]).Value;
64        return val != null ? val.Value : (int?)null;
65      }
66      set {
67        var param = (OptionalValueParameter<IntValue>)Parameters["MaximumEvaluations"];
68        param.Value = value.HasValue ? new IntValue(value.Value) : null;
69      }
70    }
71
72    public TimeSpan? MaximumExecutionTime {
73      get {
74        var val = ((OptionalValueParameter<TimeSpanValue>)Parameters["MaximumExecutionTime"]).Value;
75        return val != null ? val.Value : (TimeSpan?)null;
76      }
77      set {
78        var param = (OptionalValueParameter<TimeSpanValue>)Parameters["MaximumExecutionTime"];
79        param.Value = value.HasValue ? new TimeSpanValue(value.Value) : null;
80      }
81    }
82
83    public double? TargetQuality {
84      get {
85        var val = ((OptionalValueParameter<DoubleValue>)Parameters["TargetQuality"]).Value;
86        return val != null ? val.Value : (double?)null;
87      }
88      set {
89        var param = (OptionalValueParameter<DoubleValue>)Parameters["TargetQuality"];
90        param.Value = value.HasValue ? new DoubleValue(value.Value) : null;
91      }
92    }
93
94    protected FixedValueParameter<IntValue> MaximumPopulationSizeParameter {
95      get { return ((FixedValueParameter<IntValue>)Parameters["MaximumPopulationSize"]); }
96    }
97    public int MaximumPopulationSize {
98      get { return MaximumPopulationSizeParameter.Value.Value; }
99      set { MaximumPopulationSizeParameter.Value.Value = value; }
100    }
101
102    public bool SetSeedRandomly {
103      get { return ((FixedValueParameter<BoolValue>)Parameters["SetSeedRandomly"]).Value.Value; }
104      set { ((FixedValueParameter<BoolValue>)Parameters["SetSeedRandomly"]).Value.Value = value; }
105    }
106
107    public int Seed {
108      get { return ((FixedValueParameter<IntValue>)Parameters["Seed"]).Value.Value; }
109      set { ((FixedValueParameter<IntValue>)Parameters["Seed"]).Value.Value = value; }
110    }
111
112    public IAnalyzer Analyzer {
113      get { return ((ValueParameter<IAnalyzer>)Parameters["Analyzer"]).Value; }
114      set { ((ValueParameter<IAnalyzer>)Parameters["Analyzer"]).Value = value; }
115    }
116
117    public IConstrainedValueParameter<ISolutionModelTrainer<TPopulationContext>> SolutionModelTrainerParameter {
118      get { return (IConstrainedValueParameter<ISolutionModelTrainer<TPopulationContext>>)Parameters["SolutionModelTrainer"]; }
119    }
120
121    public IConstrainedValueParameter<ILocalSearch<TSolutionContext>> LocalSearchParameter {
122      get { return (IConstrainedValueParameter<ILocalSearch<TSolutionContext>>)Parameters["LocalSearch"]; }
123    }
124
125    [Storable]
126    private TPopulationContext context;
127    public TPopulationContext Context {
128      get { return context; }
129      protected set {
130        if (context == value) return;
131        context = value;
132        OnPropertyChanged("State");
133      }
134    }
135
136    [Storable]
137    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
138
139    [StorableConstructor]
140    protected MemPRAlgorithm(bool deserializing) : base(deserializing) { }
141    protected MemPRAlgorithm(MemPRAlgorithm<TProblem, TSolution, TPopulationContext, TSolutionContext> original, Cloner cloner) : base(original, cloner) {
142      context = cloner.Clone(original.context);
143      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
144      RegisterEventHandlers();
145    }
146    protected MemPRAlgorithm() {
147      Parameters.Add(new ValueParameter<IAnalyzer>("Analyzer", "The analyzer to apply to the population.", new MultiAnalyzer()));
148      Parameters.Add(new FixedValueParameter<IntValue>("MaximumPopulationSize", "The maximum size of the population that is evolved.", new IntValue(20)));
149      Parameters.Add(new OptionalValueParameter<IntValue>("MaximumEvaluations", "The maximum number of solution evaluations."));
150      Parameters.Add(new OptionalValueParameter<TimeSpanValue>("MaximumExecutionTime", "The maximum runtime.", new TimeSpanValue(TimeSpan.FromMinutes(1))));
151      Parameters.Add(new OptionalValueParameter<DoubleValue>("TargetQuality", "The target quality at which the algorithm terminates."));
152      Parameters.Add(new FixedValueParameter<BoolValue>("SetSeedRandomly", "Whether each run of the algorithm should be conducted with a new random seed.", new BoolValue(true)));
153      Parameters.Add(new FixedValueParameter<IntValue>("Seed", "The random number seed that is used in case SetSeedRandomly is false.", new IntValue(0)));
154      Parameters.Add(new ConstrainedValueParameter<ISolutionModelTrainer<TPopulationContext>>("SolutionModelTrainer", "The object that creates a solution model that can be sampled."));
155      Parameters.Add(new ConstrainedValueParameter<ILocalSearch<TSolutionContext>>("LocalSearch", "The local search operator to use."));
156
157      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
158      RegisterEventHandlers();
159    }
160
161    [StorableHook(HookType.AfterDeserialization)]
162    private void AfterDeserialization() {
163      RegisterEventHandlers();
164    }
165
166    private void RegisterEventHandlers() {
167      MaximumPopulationSizeParameter.Value.ValueChanged += MaximumPopulationSizeOnChanged;
168    }
169
170    private void MaximumPopulationSizeOnChanged(object sender, EventArgs eventArgs) {
171      if (ExecutionState == ExecutionState.Started || ExecutionState == ExecutionState.Paused)
172        throw new InvalidOperationException("Cannot change maximum population size before algorithm finishes.");
173      Prepare();
174    }
175
176    protected override void OnProblemChanged() {
177      base.OnProblemChanged();
178      qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
179      qualityAnalyzer.MaximizationParameter.Hidden = true;
180      qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
181      qualityAnalyzer.QualityParameter.Depth = 1;
182      qualityAnalyzer.QualityParameter.Hidden = true;
183      qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
184      qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
185
186      var multiAnalyzer = Analyzer as MultiAnalyzer;
187      if (multiAnalyzer != null) {
188        multiAnalyzer.Operators.Clear();
189        if (Problem != null) {
190          foreach (var analyzer in Problem.Operators.OfType<IAnalyzer>()) {
191            foreach (var param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
192              param.Depth = 1;
193            multiAnalyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
194          }
195        }
196        multiAnalyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
197      }
198    }
199
200    public override void Prepare() {
201      base.Prepare();
202      Results.Clear();
203      Context = null;
204    }
205
206    protected virtual TPopulationContext CreateContext() {
207      return new TPopulationContext();
208    }
209
210    protected sealed override void Run(CancellationToken token) {
211      if (Context == null) {
212        Context = CreateContext();
213        if (SetSeedRandomly) Seed = new System.Random().Next();
214        Context.Random.Reset(Seed);
215        Context.Scope.Variables.Add(new Variable("Results", Results));
216        Context.Problem = Problem;
217      }
218
219      IExecutionContext context = null;
220      foreach (var item in Problem.ExecutionContextItems)
221        context = new Core.ExecutionContext(context, item, Context.Scope);
222      context = new Core.ExecutionContext(context, this, Context.Scope);
223      Context.Parent = context;
224
225      if (!Context.Initialized) {
226        // We initialize the population with two local optima
227        while (Context.PopulationCount < 2) {
228          var child = Create(token);
229          Context.HcSteps += HillClimb(child, token);
230          Context.AddToPopulation(child);
231          Analyze(token);
232          token.ThrowIfCancellationRequested();
233          if (Terminate()) return;
234        }
235        Context.HcSteps /= 2;
236        Context.Initialized = true;
237      }
238
239      while (!Terminate()) {
240        Iterate(token);
241        Analyze(token);
242        token.ThrowIfCancellationRequested();
243      }
244    }
245
246    private void Iterate(CancellationToken token) {
247      var replaced = false;
248
249      var i1 = Context.Random.Next(Context.PopulationCount);
250      var i2 = Context.Random.Next(Context.PopulationCount);
251      while (i1 == i2) i2 = Context.Random.Next(Context.PopulationCount);
252
253      var p1 = Context.AtPopulation(i1);
254      var p2 = Context.AtPopulation(i2);
255
256      var parentDist = Dist(p1, p2);
257
258      ISingleObjectiveSolutionScope<TSolution> offspring = null;
259      int replPos = -1;
260
261      if (Context.Random.NextDouble() > parentDist) {
262        offspring = BreedAndImprove(p1, p2, token);
263        replPos = Replace(offspring, token);
264        if (replPos >= 0) {
265          replaced = true;
266          Context.ByBreeding++;
267        }
268      }
269
270      if (Context.Random.NextDouble() < parentDist) {
271        offspring = RelinkAndImprove(p1, p2, token);
272        replPos = Replace(offspring, token);
273        if (replPos >= 0) {
274          replaced = true;
275          Context.ByRelinking++;
276        }
277      }
278
279      offspring = PerformSampling(token);
280      replPos = Replace(offspring, token);
281      if (replPos >= 0) {
282        replaced = true;
283        Context.BySampling++;
284      }
285
286      if (!replaced) {
287        offspring = Create(token);
288        if (HillclimbingSuited(offspring)) {
289          HillClimb(offspring, token);
290          replPos = Replace(offspring, token);
291          if (replPos >= 0) {
292            Context.ByHillclimbing++;
293            replaced = true;
294          }
295        } else {
296          offspring = (ISingleObjectiveSolutionScope<TSolution>)Context.AtPopulation(Context.Random.Next(Context.PopulationCount)).Clone();
297          Mutate(offspring, token);
298          PerformTabuWalk(offspring, Context.HcSteps, token);
299          replPos = Replace(offspring, token);
300          if (replPos >= 0) {
301            Context.ByTabuwalking++;
302            replaced = true;
303          }
304        }
305      }
306      Context.Iterations++;
307    }
308
309    protected void Analyze(CancellationToken token) {
310      IResult res;
311      if (!Results.TryGetValue("EvaluatedSolutions", out res))
312        Results.Add(new Result("EvaluatedSolutions", new IntValue(Context.EvaluatedSolutions)));
313      else ((IntValue)res.Value).Value = Context.EvaluatedSolutions;
314      if (!Results.TryGetValue("Iterations", out res))
315        Results.Add(new Result("Iterations", new IntValue(Context.Iterations)));
316      else ((IntValue)res.Value).Value = Context.Iterations;
317      if (!Results.TryGetValue("HcSteps", out res))
318        Results.Add(new Result("HcSteps", new IntValue(Context.HcSteps)));
319      else ((IntValue)res.Value).Value = Context.HcSteps;
320      if (!Results.TryGetValue("ByBreeding", out res))
321        Results.Add(new Result("ByBreeding", new IntValue(Context.ByBreeding)));
322      else ((IntValue)res.Value).Value = Context.ByBreeding;
323      if (!Results.TryGetValue("ByRelinking", out res))
324        Results.Add(new Result("ByRelinking", new IntValue(Context.ByRelinking)));
325      else ((IntValue)res.Value).Value = Context.ByRelinking;
326      if (!Results.TryGetValue("BySampling", out res))
327        Results.Add(new Result("BySampling", new IntValue(Context.BySampling)));
328      else ((IntValue)res.Value).Value = Context.BySampling;
329      if (!Results.TryGetValue("ByHillclimbing", out res))
330        Results.Add(new Result("ByHillclimbing", new IntValue(Context.ByHillclimbing)));
331      else ((IntValue)res.Value).Value = Context.ByHillclimbing;
332      if (!Results.TryGetValue("ByTabuwalking", out res))
333        Results.Add(new Result("ByTabuwalking", new IntValue(Context.ByTabuwalking)));
334      else ((IntValue)res.Value).Value = Context.ByTabuwalking;
335
336      var sp = new ScatterPlot("Parent1 vs Offspring", "");
337      sp.Rows.Add(new ScatterPlotDataRow("corr", "", Context.BreedingStat.Select(x => new Point2D<double>(x.Item1, x.Item3))) { VisualProperties = { PointSize = 6 }});
338      if (!Results.TryGetValue("BreedingStat1", out res)) {
339        Results.Add(new Result("BreedingStat1", sp));
340      } else res.Value = sp;
341
342      sp = new ScatterPlot("Parent2 vs Offspring", "");
343      sp.Rows.Add(new ScatterPlotDataRow("corr", "", Context.BreedingStat.Select(x => new Point2D<double>(x.Item2, x.Item3))) { VisualProperties = { PointSize = 6 } });
344      if (!Results.TryGetValue("BreedingStat2", out res)) {
345        Results.Add(new Result("BreedingStat2", sp));
346      } else res.Value = sp;
347
348      sp = new ScatterPlot("Solution vs Local Optimum", "");
349      sp.Rows.Add(new ScatterPlotDataRow("corr", "", Context.HillclimbingStat.Select(x => new Point2D<double>(x.Item1, x.Item2))) { VisualProperties = { PointSize = 6 } });
350      if (!Results.TryGetValue("HillclimbingStat", out res)) {
351        Results.Add(new Result("HillclimbingStat", sp));
352      } else res.Value = sp;
353
354      sp = new ScatterPlot("Solution vs Tabu Walk", "");
355      sp.Rows.Add(new ScatterPlotDataRow("corr", "", Context.TabuwalkingStat.Select(x => new Point2D<double>(x.Item1, x.Item2))) { VisualProperties = { PointSize = 6 } });
356      if (!Results.TryGetValue("TabuwalkingStat", out res)) {
357        Results.Add(new Result("TabuwalkingStat", sp));
358      } else res.Value = sp;
359
360      RunOperator(Analyzer, Context.Scope, token);
361    }
362
363    protected int Replace(ISingleObjectiveSolutionScope<TSolution> child, CancellationToken token) {
364      if (double.IsNaN(child.Fitness)) {
365        Evaluate(child, token);
366        Context.IncrementEvaluatedSolutions(1);
367      }
368      if (IsBetter(child.Fitness, Context.BestQuality)) {
369        Context.BestQuality = child.Fitness;
370        Context.BestSolution = (TSolution)child.Solution.Clone();
371      }
372
373      var popSize = MaximumPopulationSize;
374      if (Context.Population.All(p => !Eq(p, child))) {
375
376        if (Context.PopulationCount < popSize) {
377          Context.AddToPopulation(child);
378          return Context.PopulationCount - 1;
379        }
380       
381        // The set of replacement candidates consists of all solutions at least as good as the new one
382        var candidates = Context.Population.Select((p, i) => new { Index = i, Individual = p })
383                                         .Where(x => x.Individual.Fitness == child.Fitness
384                                           || IsBetter(child, x.Individual)).ToList();
385        if (candidates.Count == 0) return -1;
386
387        var repCand = -1;
388        var avgChildDist = 0.0;
389        var minChildDist = double.MaxValue;
390        var plateau = new List<int>();
391        var worstPlateau = -1;
392        var minAvgPlateauDist = double.MaxValue;
393        var minPlateauDist = double.MaxValue;
394        // If there are equally good solutions it is first tried to replace one of those
395        // The criteria for replacement is that the new solution has better average distance
396        // to all other solutions at this "plateau"
397        foreach (var c in candidates.Where(x => x.Individual.Fitness == child.Fitness)) {
398          var dist = Dist(c.Individual, child);
399          avgChildDist += dist;
400          if (dist < minChildDist) minChildDist = dist;
401          plateau.Add(c.Index);
402        }
403        if (plateau.Count > 2) {
404          avgChildDist /= plateau.Count;
405          foreach (var p in plateau) {
406            var avgDist = 0.0;
407            var minDist = double.MaxValue;
408            foreach (var q in plateau) {
409              if (p == q) continue;
410              var dist = Dist(Context.AtPopulation(p), Context.AtPopulation(q));
411              avgDist += dist;
412              if (dist < minDist) minDist = dist;
413            }
414
415            var d = Dist(Context.AtPopulation(p), child);
416            avgDist += d;
417            avgDist /= plateau.Count;
418            if (d < minDist) minDist = d;
419
420            if (minDist < minPlateauDist || (minDist == minPlateauDist && avgDist < avgChildDist)) {
421              minAvgPlateauDist = avgDist;
422              minPlateauDist = minDist;
423              worstPlateau = p;
424            }
425          }
426          if (minPlateauDist < minChildDist || (minPlateauDist == minChildDist && minAvgPlateauDist < avgChildDist))
427            repCand = worstPlateau;
428        }
429
430        if (repCand < 0) {
431          // If no solution at the same plateau were identified for replacement
432          // a worse solution with smallest distance is chosen
433          var minDist = double.MaxValue;
434          foreach (var c in candidates.Where(x => IsBetter(child, x.Individual))) {
435            var d = Dist(c.Individual, child);
436            if (d < minDist) {
437              minDist = d;
438              repCand = c.Index;
439            }
440          }
441        }
442
443        // If no replacement was identified, this can only mean that there are
444        // no worse solutions and those on the same plateau are all better
445        // stretched out than the new one
446        if (repCand < 0) return -1;
447       
448        Context.ReplaceAtPopulation(repCand, child);
449        return repCand;
450      }
451      return -1;
452    }
453
454    [MethodImpl(MethodImplOptions.AggressiveInlining)]
455    protected bool IsBetter(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b) {
456      return IsBetter(a.Fitness, b.Fitness);
457    }
458    [MethodImpl(MethodImplOptions.AggressiveInlining)]
459    protected bool IsBetter(double a, double b) {
460      return double.IsNaN(b) && !double.IsNaN(a)
461        || Problem.Maximization && a > b
462        || !Problem.Maximization && a < b;
463    }
464   
465    protected abstract bool Eq(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b);
466    protected abstract double Dist(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b);
467    protected abstract ISingleObjectiveSolutionScope<TSolution> ToScope(TSolution code, double fitness = double.NaN);
468    protected abstract ISolutionSubspace<TSolution> CalculateSubspace(IEnumerable<TSolution> solutions, bool inverse = false);
469    protected virtual void Evaluate(ISingleObjectiveSolutionScope<TSolution> scope, CancellationToken token) {
470      var prob = Problem as ISingleObjectiveProblemDefinition;
471      if (prob != null) {
472        var ind = new SingleEncodingIndividual(prob.Encoding, scope);
473        scope.Fitness = prob.Evaluate(ind, Context.Random);
474      } else RunOperator(Problem.Evaluator, scope, token);
475    }
476
477    #region Create
478    protected virtual ISingleObjectiveSolutionScope<TSolution> Create(CancellationToken token) {
479      var child = ToScope(null);
480      RunOperator(Problem.SolutionCreator, child, token);
481      return child;
482    }
483    #endregion
484
485    #region Improve
486    protected virtual int HillClimb(ISingleObjectiveSolutionScope<TSolution> scope, CancellationToken token, ISolutionSubspace<TSolution> subspace = null) {
487      if (double.IsNaN(scope.Fitness)) {
488        Evaluate(scope, token);
489        Context.IncrementEvaluatedSolutions(1);
490      }
491      var before = scope.Fitness;
492      var lscontext = Context.CreateSingleSolutionContext(scope);
493      LocalSearchParameter.Value.Optimize(lscontext);
494      var after = scope.Fitness;
495      Context.HillclimbingStat.Add(Tuple.Create(before, after));
496      Context.IncrementEvaluatedSolutions(lscontext.EvaluatedSolutions);
497      return lscontext.EvaluatedSolutions;
498    }
499
500    protected virtual void PerformTabuWalk(ISingleObjectiveSolutionScope<TSolution> scope, int steps, CancellationToken token, ISolutionSubspace<TSolution> subspace = null) {
501      if (double.IsNaN(scope.Fitness)) {
502        Evaluate(scope, token);
503        Context.IncrementEvaluatedSolutions(1);
504      }
505      var before = scope.Fitness;
506      var newScope = (ISingleObjectiveSolutionScope<TSolution>)scope.Clone();
507      var newSteps = TabuWalk(newScope, steps, token, subspace);
508      Context.TabuwalkingStat.Add(Tuple.Create(before, newScope.Fitness));
509      //Context.HcSteps = (int)Math.Ceiling(Context.HcSteps * (1.0 + Context.TabuwalkingStat.Count) / (2.0 + Context.TabuwalkingStat.Count) + newSteps / (2.0 + Context.TabuwalkingStat.Count));
510      if (IsBetter(newScope, scope) || (newScope.Fitness == scope.Fitness && Dist(newScope, scope) > 0))
511        scope.Adopt(newScope);
512    }
513    protected abstract int TabuWalk(ISingleObjectiveSolutionScope<TSolution> scope, int maxEvals, CancellationToken token, ISolutionSubspace<TSolution> subspace = null);
514    protected virtual void TabuClimb(ISingleObjectiveSolutionScope<TSolution> scope, int steps, CancellationToken token, ISolutionSubspace<TSolution> subspace = null) {
515      if (double.IsNaN(scope.Fitness)) {
516        Evaluate(scope, token);
517        Context.IncrementEvaluatedSolutions(1);
518      }
519      var before = scope.Fitness;
520      var newScope = (ISingleObjectiveSolutionScope<TSolution>)scope.Clone();
521      var newSteps = TabuWalk(newScope, steps, token, subspace);
522      Context.TabuwalkingStat.Add(Tuple.Create(before, newScope.Fitness));
523      //Context.HcSteps = (int)Math.Ceiling(Context.HcSteps * (1.0 + Context.TabuwalkingStat.Count) / (2.0 + Context.TabuwalkingStat.Count) + newSteps / (2.0 + Context.TabuwalkingStat.Count));
524      if (IsBetter(newScope, scope) || (newScope.Fitness == scope.Fitness && Dist(newScope, scope) > 0))
525        scope.Adopt(newScope);
526    }
527    #endregion
528   
529    #region Breed
530    protected virtual ISingleObjectiveSolutionScope<TSolution> PerformBreeding(CancellationToken token) {
531      if (Context.PopulationCount < 2) throw new InvalidOperationException("Cannot breed from population with less than 2 individuals.");
532      var i1 = Context.Random.Next(Context.PopulationCount);
533      var i2 = Context.Random.Next(Context.PopulationCount);
534      while (i1 == i2) i2 = Context.Random.Next(Context.PopulationCount);
535
536      var p1 = Context.AtPopulation(i1);
537      var p2 = Context.AtPopulation(i2);
538
539      if (double.IsNaN(p1.Fitness)) {
540        Evaluate(p1, token);
541        Context.IncrementEvaluatedSolutions(1);
542      }
543      if (double.IsNaN(p2.Fitness)) {
544        Evaluate(p2, token);
545        Context.IncrementEvaluatedSolutions(1);
546      }
547
548      return BreedAndImprove(p1, p2, token);
549    }
550
551    protected virtual ISingleObjectiveSolutionScope<TSolution> BreedAndImprove(ISingleObjectiveSolutionScope<TSolution> p1, ISingleObjectiveSolutionScope<TSolution> p2, CancellationToken token) {
552      var offspring = Cross(p1, p2, token);
553      var subspace = CalculateSubspace(new[] { p1.Solution, p2.Solution });
554      if (Context.Random.NextDouble() < MutationProbabilityMagicConst) {
555        Mutate(offspring, token, subspace); // mutate the solutions, especially to widen the sub-space
556      }
557      if (double.IsNaN(offspring.Fitness)) {
558        Evaluate(offspring, token);
559        Context.IncrementEvaluatedSolutions(1);
560      }
561      Context.BreedingStat.Add(Tuple.Create(p1.Fitness, p2.Fitness, offspring.Fitness));
562      if ((IsBetter(offspring, p1) && IsBetter(offspring, p2))
563        || Context.Population.Any(p => IsBetter(offspring, p))) return offspring;
564
565      if (HillclimbingSuited(offspring))
566        HillClimb(offspring, token, subspace); // perform hillclimb in the solution sub-space
567      return offspring;
568    }
569
570    protected abstract ISingleObjectiveSolutionScope<TSolution> Cross(ISingleObjectiveSolutionScope<TSolution> p1, ISingleObjectiveSolutionScope<TSolution> p2, CancellationToken token);
571    protected abstract void Mutate(ISingleObjectiveSolutionScope<TSolution> offspring, CancellationToken token, ISolutionSubspace<TSolution> subspace = null);
572    #endregion
573
574    #region Relink
575    protected virtual ISingleObjectiveSolutionScope<TSolution> PerformRelinking(CancellationToken token) {
576      if (Context.PopulationCount < 2) throw new InvalidOperationException("Cannot breed from population with less than 2 individuals.");
577      var i1 = Context.Random.Next(Context.PopulationCount);
578      var i2 = Context.Random.Next(Context.PopulationCount);
579      while (i1 == i2) i2 = Context.Random.Next(Context.PopulationCount);
580
581      var p1 = Context.AtPopulation(i1);
582      var p2 = Context.AtPopulation(i2);
583
584      return RelinkAndImprove(p1, p2, token);
585    }
586
587    protected virtual ISingleObjectiveSolutionScope<TSolution> RelinkAndImprove(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b, CancellationToken token) {
588      var child = Relink(a, b, token);
589      if (IsBetter(child, a) && IsBetter(child, b)) return child;
590
591      var dist1 = Dist(child, a);
592      var dist2 = Dist(child, b);
593      if (dist1 > 0 && dist2 > 0) {
594        var subspace = CalculateSubspace(new[] { a.Solution, b.Solution }, inverse: true);
595        if (HillclimbingSuited(child)) {
596          HillClimb(child, token, subspace); // perform hillclimb in solution sub-space
597        }
598      }
599      return child;
600    }
601
602    protected abstract ISingleObjectiveSolutionScope<TSolution> Relink(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b, CancellationToken token);
603    #endregion
604
605    #region Sample
606    protected virtual ISingleObjectiveSolutionScope<TSolution> PerformSampling(CancellationToken token) {
607      SolutionModelTrainerParameter.Value.TrainModel(Context);
608      var sample = ToScope(Context.Model.Sample());
609      Evaluate(sample, token);
610      Context.IncrementEvaluatedSolutions(1);
611      if (Context.Population.Any(p => IsBetter(sample, p) || sample.Fitness == p.Fitness)) return sample;
612
613      if (HillclimbingSuited(sample)) {
614        var subspace = CalculateSubspace(Context.Population.Select(x => x.Solution));
615        HillClimb(sample, token, subspace);
616      }
617      return sample;
618    }
619    #endregion
620
621    protected bool HillclimbingSuited(ISingleObjectiveSolutionScope<TSolution> scope) {
622      return Context.Random.NextDouble() < ProbabilityAccept(scope, Context.HillclimbingStat);
623    }
624    protected bool HillclimbingSuited(double startingFitness) {
625      return Context.Random.NextDouble() < ProbabilityAccept(startingFitness, Context.HillclimbingStat);
626    }
627    protected bool TabuwalkingSuited(ISingleObjectiveSolutionScope<TSolution> scope) {
628      return Context.Random.NextDouble() < ProbabilityAccept(scope, Context.TabuwalkingStat);
629    }
630    protected bool TabuwalkingSuited(double startingFitness) {
631      return Context.Random.NextDouble() < ProbabilityAccept(startingFitness, Context.TabuwalkingStat);
632    }
633
634    protected double ProbabilityAccept(ISingleObjectiveSolutionScope<TSolution> scope, IList<Tuple<double, double>> data) {
635      if (double.IsNaN(scope.Fitness)) {
636        Evaluate(scope, CancellationToken.None);
637        Context.IncrementEvaluatedSolutions(1);
638      }
639      return ProbabilityAccept(scope.Fitness, data);
640    }
641    protected double ProbabilityAccept(double startingFitness, IList<Tuple<double, double>> data) {
642      if (data.Count < 10) return 1.0;
643      int[] clusterValues;
644      var centroids = CkMeans1D.Cluster(data.Select(x => x.Item1).ToArray(), 2, out clusterValues);
645      var cluster = Math.Abs(startingFitness - centroids.First().Key) < Math.Abs(startingFitness - centroids.Last().Key) ? centroids.First().Value : centroids.Last().Value;
646
647      var samples = 0;
648      double meanStart = 0, meanStartOld = 0, meanEnd = 0, meanEndOld = 0;
649      double varStart = 0, varStartOld = 0, varEnd = 0, varEndOld = 0;
650      for (var i = 0; i < data.Count; i++) {
651        if (clusterValues[i] != cluster) continue;
652
653        samples++;
654        var x = data[i].Item1;
655        var y = data[i].Item2;
656
657        if (samples == 1) {
658          meanStartOld = x;
659          meanEndOld = y;
660        } else {
661          meanStart = meanStartOld + (x - meanStartOld) / samples;
662          meanEnd = meanEndOld + (x - meanEndOld) / samples;
663          varStart = varStartOld + (x - meanStartOld) * (x - meanStart) / (samples - 1);
664          varEnd = varEndOld + (x - meanEndOld) * (x - meanEnd) / (samples - 1);
665
666          meanStartOld = meanStart;
667          meanEndOld = meanEnd;
668          varStartOld = varStart;
669          varEndOld = varEnd;
670        }
671      }
672      if (samples < 5) return 1.0;
673      var cov = data.Select((v, i) => new { Index = i, Value = v }).Where(x => clusterValues[x.Index] == cluster).Select(x => x.Value).Sum(x => (x.Item1 - meanStart) * (x.Item2 - meanEnd)) / data.Count;
674
675      var biasedMean = meanEnd + cov / varStart * (startingFitness - meanStart);
676      var biasedStdev = Math.Sqrt(varEnd - (cov * cov) / varStart);
677
678      if (Problem.Maximization) {
679        var goal = Context.Population.Min(x => x.Fitness);
680        var z = (goal - biasedMean) / biasedStdev;
681        return 1.0 - Phi(z); // P(X >= z)
682      } else {
683        var goal = Context.Population.Max(x => x.Fitness);
684        var z = (goal - biasedMean) / biasedStdev;
685        return Phi(z); // P(X <= z)
686      }
687    }
688
689    protected virtual bool Terminate() {
690      return MaximumEvaluations.HasValue && Context.EvaluatedSolutions >= MaximumEvaluations.Value
691        || MaximumExecutionTime.HasValue && ExecutionTime >= MaximumExecutionTime.Value
692        || TargetQuality.HasValue && (Problem.Maximization && Context.BestQuality >= TargetQuality.Value
693                                  || !Problem.Maximization && Context.BestQuality <= TargetQuality.Value);
694    }
695
696    public event PropertyChangedEventHandler PropertyChanged;
697    protected void OnPropertyChanged(string property) {
698      var handler = PropertyChanged;
699      if (handler != null) handler(this, new PropertyChangedEventArgs(property));
700    }
701
702    #region Engine Helper
703    protected void RunOperator(IOperator op, IScope scope, CancellationToken cancellationToken) {
704      var stack = new Stack<IOperation>();
705      stack.Push(Context.CreateChildOperation(op, scope));
706
707      while (stack.Count > 0) {
708        cancellationToken.ThrowIfCancellationRequested();
709
710        var next = stack.Pop();
711        if (next is OperationCollection) {
712          var coll = (OperationCollection)next;
713          for (int i = coll.Count - 1; i >= 0; i--)
714            if (coll[i] != null) stack.Push(coll[i]);
715        } else if (next is IAtomicOperation) {
716          var operation = (IAtomicOperation)next;
717          try {
718            next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
719          } catch (Exception ex) {
720            stack.Push(operation);
721            if (ex is OperationCanceledException) throw ex;
722            else throw new OperatorExecutionException(operation.Operator, ex);
723          }
724          if (next != null) stack.Push(next);
725        }
726      }
727    }
728    #endregion
729
730    #region Math Helper
731    // normal distribution CDF (left of x) for N(0;1) standard normal distribution
732    // from http://www.johndcook.com/blog/csharp_phi/
733    // license: "This code is in the public domain. Do whatever you want with it, no strings attached."
734    // added: 2016-11-19 21:46 CET
735    protected static double Phi(double x) {
736      // constants
737      double a1 = 0.254829592;
738      double a2 = -0.284496736;
739      double a3 = 1.421413741;
740      double a4 = -1.453152027;
741      double a5 = 1.061405429;
742      double p = 0.3275911;
743
744      // Save the sign of x
745      int sign = 1;
746      if (x < 0)
747        sign = -1;
748      x = Math.Abs(x) / Math.Sqrt(2.0);
749
750      // A&S formula 7.1.26
751      double t = 1.0 / (1.0 + p * x);
752      double y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * Math.Exp(-x * x);
753
754      return 0.5 * (1.0 + sign * y);
755    }
756    #endregion
757  }
758}
Note: See TracBrowser for help on using the repository browser.