Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2701:

  • Worked on MemPR algorithm for permutations
  • Refactored TSP
File size: 33.4 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        }
234        Context.HcSteps /= 2;
235        Context.Initialized = true;
236      }
237
238      while (!Terminate()) {
239        Iterate(token);
240        Analyze(token);
241        token.ThrowIfCancellationRequested();
242      }
243    }
244
245    private void Iterate(CancellationToken token) {
246      var replaced = false;
247
248      var i1 = Context.Random.Next(Context.PopulationCount);
249      var i2 = Context.Random.Next(Context.PopulationCount);
250      while (i1 == i2) i2 = Context.Random.Next(Context.PopulationCount);
251
252      var p1 = Context.AtPopulation(i1);
253      var p2 = Context.AtPopulation(i2);
254
255      var parentDist = Dist(p1, p2);
256
257      ISingleObjectiveSolutionScope<TSolution> offspring = null;
258      int replPos = -1;
259
260      if (Context.Random.NextDouble() > parentDist) {
261        offspring = BreedAndImprove(p1, p2, token);
262        replPos = Replace(offspring, token);
263        if (replPos >= 0) {
264          replaced = true;
265          Context.ByBreeding++;
266        }
267      }
268
269      if (Context.Random.NextDouble() < parentDist) {
270        offspring = RelinkAndImprove(p1, p2, token);
271        replPos = Replace(offspring, token);
272        if (replPos >= 0) {
273          replaced = true;
274          Context.ByRelinking++;
275        }
276      }
277
278      offspring = PerformSampling(token);
279      replPos = Replace(offspring, token);
280      if (replPos >= 0) {
281        replaced = true;
282        Context.BySampling++;
283      }
284
285      if (!replaced) {
286        offspring = Create(token);
287        if (HillclimbingSuited(offspring)) {
288          HillClimb(offspring, token);
289          replPos = Replace(offspring, token);
290          if (replPos >= 0) {
291            Context.ByHillclimbing++;
292            replaced = true;
293          }
294        } else {
295          offspring = (ISingleObjectiveSolutionScope<TSolution>)Context.AtPopulation(Context.Random.Next(Context.PopulationCount)).Clone();
296          Mutate(offspring, token);
297          PerformTabuWalk(offspring, Context.HcSteps, token);
298          replPos = Replace(offspring, token);
299          if (replPos >= 0) {
300            Context.ByTabuwalking++;
301            replaced = true;
302          }
303        }
304      }
305      Context.Iterations++;
306    }
307
308    protected void Analyze(CancellationToken token) {
309      IResult res;
310      if (!Results.TryGetValue("EvaluatedSolutions", out res))
311        Results.Add(new Result("EvaluatedSolutions", new IntValue(Context.EvaluatedSolutions)));
312      else ((IntValue)res.Value).Value = Context.EvaluatedSolutions;
313      if (!Results.TryGetValue("Iterations", out res))
314        Results.Add(new Result("Iterations", new IntValue(Context.Iterations)));
315      else ((IntValue)res.Value).Value = Context.Iterations;
316      if (!Results.TryGetValue("ByBreeding", out res))
317        Results.Add(new Result("ByBreeding", new IntValue(Context.ByBreeding)));
318      else ((IntValue)res.Value).Value = Context.ByBreeding;
319      if (!Results.TryGetValue("ByRelinking", out res))
320        Results.Add(new Result("ByRelinking", new IntValue(Context.ByRelinking)));
321      else ((IntValue)res.Value).Value = Context.ByRelinking;
322      if (!Results.TryGetValue("BySampling", out res))
323        Results.Add(new Result("BySampling", new IntValue(Context.BySampling)));
324      else ((IntValue)res.Value).Value = Context.BySampling;
325      if (!Results.TryGetValue("ByHillclimbing", out res))
326        Results.Add(new Result("ByHillclimbing", new IntValue(Context.ByHillclimbing)));
327      else ((IntValue)res.Value).Value = Context.ByHillclimbing;
328      if (!Results.TryGetValue("ByTabuwalking", out res))
329        Results.Add(new Result("ByTabuwalking", new IntValue(Context.ByTabuwalking)));
330      else ((IntValue)res.Value).Value = Context.ByTabuwalking;
331
332      var sp = new ScatterPlot("Parent1 vs Offspring", "");
333      sp.Rows.Add(new ScatterPlotDataRow("corr", "", Context.BreedingStat.Select(x => new Point2D<double>(x.Item1, x.Item3))) { VisualProperties = { PointSize = 6 }});
334      if (!Results.TryGetValue("BreedingStat1", out res)) {
335        Results.Add(new Result("BreedingStat1", sp));
336      } else res.Value = sp;
337
338      sp = new ScatterPlot("Parent2 vs Offspring", "");
339      sp.Rows.Add(new ScatterPlotDataRow("corr", "", Context.BreedingStat.Select(x => new Point2D<double>(x.Item2, x.Item3))) { VisualProperties = { PointSize = 6 } });
340      if (!Results.TryGetValue("BreedingStat2", out res)) {
341        Results.Add(new Result("BreedingStat2", sp));
342      } else res.Value = sp;
343
344      sp = new ScatterPlot("Solution vs Local Optimum", "");
345      sp.Rows.Add(new ScatterPlotDataRow("corr", "", Context.HillclimbingStat.Select(x => new Point2D<double>(x.Item1, x.Item2))) { VisualProperties = { PointSize = 6 } });
346      if (!Results.TryGetValue("HillclimbingStat", out res)) {
347        Results.Add(new Result("HillclimbingStat", sp));
348      } else res.Value = sp;
349
350      sp = new ScatterPlot("Solution vs Tabu Walk", "");
351      sp.Rows.Add(new ScatterPlotDataRow("corr", "", Context.TabuwalkingStat.Select(x => new Point2D<double>(x.Item1, x.Item2))) { VisualProperties = { PointSize = 6 } });
352      if (!Results.TryGetValue("TabuwalkingStat", out res)) {
353        Results.Add(new Result("TabuwalkingStat", sp));
354      } else res.Value = sp;
355
356      RunOperator(Analyzer, Context.Scope, token);
357    }
358
359    protected int Replace(ISingleObjectiveSolutionScope<TSolution> child, CancellationToken token) {
360      if (double.IsNaN(child.Fitness)) {
361        Evaluate(child, token);
362        Context.IncrementEvaluatedSolutions(1);
363      }
364      if (IsBetter(child.Fitness, Context.BestQuality)) {
365        Context.BestQuality = child.Fitness;
366        Context.BestSolution = (TSolution)child.Solution.Clone();
367      }
368
369      var popSize = MaximumPopulationSize;
370      if (Context.Population.All(p => !Eq(p, child))) {
371
372        if (Context.PopulationCount < popSize) {
373          Context.AddToPopulation(child);
374          return Context.PopulationCount - 1;
375        }
376       
377        // The set of replacement candidates consists of all solutions at least as good as the new one
378        var candidates = Context.Population.Select((p, i) => new { Index = i, Individual = p })
379                                         .Where(x => x.Individual.Fitness == child.Fitness
380                                           || IsBetter(child, x.Individual)).ToList();
381        if (candidates.Count == 0) return -1;
382
383        var repCand = -1;
384        var avgChildDist = 0.0;
385        var minChildDist = double.MaxValue;
386        var plateau = new List<int>();
387        var worstPlateau = -1;
388        var minAvgPlateauDist = double.MaxValue;
389        var minPlateauDist = double.MaxValue;
390        // If there are equally good solutions it is first tried to replace one of those
391        // The criteria for replacement is that the new solution has better average distance
392        // to all other solutions at this "plateau"
393        foreach (var c in candidates.Where(x => x.Individual.Fitness == child.Fitness)) {
394          var dist = Dist(c.Individual, child);
395          avgChildDist += dist;
396          if (dist < minChildDist) minChildDist = dist;
397          plateau.Add(c.Index);
398        }
399        if (plateau.Count > 2) {
400          avgChildDist /= plateau.Count;
401          foreach (var p in plateau) {
402            var avgDist = 0.0;
403            var minDist = double.MaxValue;
404            foreach (var q in plateau) {
405              if (p == q) continue;
406              var dist = Dist(Context.AtPopulation(p), Context.AtPopulation(q));
407              avgDist += dist;
408              if (dist < minDist) minDist = dist;
409            }
410
411            var d = Dist(Context.AtPopulation(p), child);
412            avgDist += d;
413            avgDist /= plateau.Count;
414            if (d < minDist) minDist = d;
415
416            if (minDist < minPlateauDist || (minDist == minPlateauDist && avgDist < avgChildDist)) {
417              minAvgPlateauDist = avgDist;
418              minPlateauDist = minDist;
419              worstPlateau = p;
420            }
421          }
422          if (minPlateauDist < minChildDist || (minPlateauDist == minChildDist && minAvgPlateauDist < avgChildDist))
423            repCand = worstPlateau;
424        }
425
426        if (repCand < 0) {
427          // If no solution at the same plateau were identified for replacement
428          // a worse solution with smallest distance is chosen
429          var minDist = double.MaxValue;
430          foreach (var c in candidates.Where(x => IsBetter(child, x.Individual))) {
431            var d = Dist(c.Individual, child);
432            if (d < minDist) {
433              minDist = d;
434              repCand = c.Index;
435            }
436          }
437        }
438
439        // If no replacement was identified, this can only mean that there are
440        // no worse solutions and those on the same plateau are all better
441        // stretched out than the new one
442        if (repCand < 0) return -1;
443       
444        Context.ReplaceAtPopulation(repCand, child);
445        return repCand;
446      }
447      return -1;
448    }
449
450    [MethodImpl(MethodImplOptions.AggressiveInlining)]
451    protected bool IsBetter(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b) {
452      return IsBetter(a.Fitness, b.Fitness);
453    }
454    [MethodImpl(MethodImplOptions.AggressiveInlining)]
455    protected bool IsBetter(double a, double b) {
456      return double.IsNaN(b) && !double.IsNaN(a)
457        || Problem.Maximization && a > b
458        || !Problem.Maximization && a < b;
459    }
460   
461    protected abstract bool Eq(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b);
462    protected abstract double Dist(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b);
463    protected abstract ISingleObjectiveSolutionScope<TSolution> ToScope(TSolution code, double fitness = double.NaN);
464    protected abstract ISolutionSubspace<TSolution> CalculateSubspace(IEnumerable<TSolution> solutions, bool inverse = false);
465    protected virtual void Evaluate(ISingleObjectiveSolutionScope<TSolution> scope, CancellationToken token) {
466      var prob = Problem as ISingleObjectiveProblemDefinition;
467      if (prob != null) {
468        var ind = new SingleEncodingIndividual(prob.Encoding, scope);
469        scope.Fitness = prob.Evaluate(ind, Context.Random);
470      } else RunOperator(Problem.Evaluator, scope, token);
471    }
472
473    #region Create
474    protected virtual ISingleObjectiveSolutionScope<TSolution> Create(CancellationToken token) {
475      var child = ToScope(null);
476      RunOperator(Problem.SolutionCreator, child, token);
477      return child;
478    }
479    #endregion
480
481    #region Improve
482    protected virtual int HillClimb(ISingleObjectiveSolutionScope<TSolution> scope, CancellationToken token, ISolutionSubspace<TSolution> subspace = null) {
483      if (double.IsNaN(scope.Fitness)) {
484        Evaluate(scope, token);
485        Context.IncrementEvaluatedSolutions(1);
486      }
487      var before = scope.Fitness;
488      var lscontext = Context.CreateSingleSolutionContext(scope);
489      LocalSearchParameter.Value.Optimize(lscontext);
490      var after = scope.Fitness;
491      Context.HillclimbingStat.Add(Tuple.Create(before, after));
492      Context.IncrementEvaluatedSolutions(lscontext.EvaluatedSolutions);
493      return lscontext.Iterations;
494    }
495
496    protected virtual void PerformTabuWalk(ISingleObjectiveSolutionScope<TSolution> scope, int steps, CancellationToken token, ISolutionSubspace<TSolution> subspace = null) {
497      if (double.IsNaN(scope.Fitness)) {
498        Evaluate(scope, token);
499        Context.IncrementEvaluatedSolutions(1);
500      }
501      var before = scope.Fitness;
502      var newScope = (ISingleObjectiveSolutionScope<TSolution>)scope.Clone();
503      TabuWalk(newScope, steps, token, subspace);
504      Context.TabuwalkingStat.Add(Tuple.Create(before, newScope.Fitness));
505      if (IsBetter(newScope, scope) || (newScope.Fitness == scope.Fitness && Dist(newScope, scope) > 0))
506        scope.Adopt(newScope);
507    }
508    protected abstract void TabuWalk(ISingleObjectiveSolutionScope<TSolution> scope, int steps, CancellationToken token, ISolutionSubspace<TSolution> subspace = null);
509    protected virtual void TabuClimb(ISingleObjectiveSolutionScope<TSolution> scope, int steps, CancellationToken token, ISolutionSubspace<TSolution> subspace = null) {
510      if (double.IsNaN(scope.Fitness)) {
511        Evaluate(scope, token);
512        Context.IncrementEvaluatedSolutions(1);
513      }
514      var before = scope.Fitness;
515      var newScope = (ISingleObjectiveSolutionScope<TSolution>)scope.Clone();
516      TabuWalk(newScope, steps, token, subspace);
517      Context.TabuwalkingStat.Add(Tuple.Create(before, newScope.Fitness));
518      if (IsBetter(newScope, scope) || (newScope.Fitness == scope.Fitness && Dist(newScope, scope) > 0))
519        scope.Adopt(newScope);
520    }
521    #endregion
522   
523    #region Breed
524    protected virtual ISingleObjectiveSolutionScope<TSolution> PerformBreeding(CancellationToken token) {
525      if (Context.PopulationCount < 2) throw new InvalidOperationException("Cannot breed from population with less than 2 individuals.");
526      var i1 = Context.Random.Next(Context.PopulationCount);
527      var i2 = Context.Random.Next(Context.PopulationCount);
528      while (i1 == i2) i2 = Context.Random.Next(Context.PopulationCount);
529
530      var p1 = Context.AtPopulation(i1);
531      var p2 = Context.AtPopulation(i2);
532
533      if (double.IsNaN(p1.Fitness)) {
534        Evaluate(p1, token);
535        Context.IncrementEvaluatedSolutions(1);
536      }
537      if (double.IsNaN(p2.Fitness)) {
538        Evaluate(p2, token);
539        Context.IncrementEvaluatedSolutions(1);
540      }
541
542      return BreedAndImprove(p1, p2, token);
543    }
544
545    protected virtual ISingleObjectiveSolutionScope<TSolution> BreedAndImprove(ISingleObjectiveSolutionScope<TSolution> p1, ISingleObjectiveSolutionScope<TSolution> p2, CancellationToken token) {
546      var offspring = Cross(p1, p2, token);
547      var subspace = CalculateSubspace(new[] { p1.Solution, p2.Solution });
548      if (Context.Random.NextDouble() < MutationProbabilityMagicConst) {
549        Mutate(offspring, token, subspace); // mutate the solutions, especially to widen the sub-space
550      }
551      if (double.IsNaN(offspring.Fitness)) {
552        Evaluate(offspring, token);
553        Context.IncrementEvaluatedSolutions(1);
554      }
555      Context.BreedingStat.Add(Tuple.Create(p1.Fitness, p2.Fitness, offspring.Fitness));
556      if ((IsBetter(offspring, p1) && IsBetter(offspring, p2))
557        || Context.Population.Any(p => IsBetter(offspring, p))) return offspring;
558
559      if (IsBetter(offspring.Fitness, Context.BestQuality))
560        HillClimb(offspring, token); // perform hillclimb in full solution space
561      else if (HillclimbingSuited(offspring))
562        HillClimb(offspring, token, subspace); // perform hillclimb in the solution sub-space
563      return offspring;
564    }
565
566    protected abstract ISingleObjectiveSolutionScope<TSolution> Cross(ISingleObjectiveSolutionScope<TSolution> p1, ISingleObjectiveSolutionScope<TSolution> p2, CancellationToken token);
567    protected abstract void Mutate(ISingleObjectiveSolutionScope<TSolution> offspring, CancellationToken token, ISolutionSubspace<TSolution> subspace = null);
568    #endregion
569
570    #region Relink
571    protected virtual ISingleObjectiveSolutionScope<TSolution> PerformRelinking(CancellationToken token) {
572      if (Context.PopulationCount < 2) throw new InvalidOperationException("Cannot breed from population with less than 2 individuals.");
573      var i1 = Context.Random.Next(Context.PopulationCount);
574      var i2 = Context.Random.Next(Context.PopulationCount);
575      while (i1 == i2) i2 = Context.Random.Next(Context.PopulationCount);
576
577      var p1 = Context.AtPopulation(i1);
578      var p2 = Context.AtPopulation(i2);
579
580      return RelinkAndImprove(p1, p2, token);
581    }
582
583    protected virtual ISingleObjectiveSolutionScope<TSolution> RelinkAndImprove(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b, CancellationToken token) {
584      var child = Relink(a, b, token);
585      if (IsBetter(child, a) && IsBetter(child, b)) return child;
586
587      var dist1 = Dist(child, a);
588      var dist2 = Dist(child, b);
589      if (dist1 > 0 && dist2 > 0) {
590        var subspace = CalculateSubspace(new[] { a.Solution, b.Solution }, inverse: true);
591        if (IsBetter(child.Fitness, Context.BestQuality))
592          HillClimb(child, token); // perform hillclimb in full solution space
593        else if (HillclimbingSuited(child)) {
594          HillClimb(child, token, subspace); // perform hillclimb in solution sub-space
595        }
596      }
597      return child;
598    }
599
600    protected abstract ISingleObjectiveSolutionScope<TSolution> Relink(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b, CancellationToken token);
601    #endregion
602
603    #region Sample
604    protected virtual ISingleObjectiveSolutionScope<TSolution> PerformSampling(CancellationToken token) {
605      SolutionModelTrainerParameter.Value.TrainModel(Context);
606      var sample = ToScope(Context.Model.Sample());
607      Evaluate(sample, token);
608      Context.IncrementEvaluatedSolutions(1);
609      if (Context.Population.Any(p => IsBetter(sample, p) || sample.Fitness == p.Fitness)) return sample;
610
611      if (HillclimbingSuited(sample)) {
612        var subspace = CalculateSubspace(Context.Population.Select(x => x.Solution));
613        HillClimb(sample, token, subspace);
614      }
615      return sample;
616    }
617    #endregion
618
619    protected bool HillclimbingSuited(ISingleObjectiveSolutionScope<TSolution> scope) {
620      return Context.Random.NextDouble() < ProbabilityAccept(scope, Context.HillclimbingStat);
621    }
622    protected bool HillclimbingSuited(double startingFitness) {
623      return Context.Random.NextDouble() < ProbabilityAccept(startingFitness, Context.HillclimbingStat);
624    }
625    protected bool TabuwalkingSuited(ISingleObjectiveSolutionScope<TSolution> scope) {
626      return Context.Random.NextDouble() < ProbabilityAccept(scope, Context.TabuwalkingStat);
627    }
628    protected bool TabuwalkingSuited(double startingFitness) {
629      return Context.Random.NextDouble() < ProbabilityAccept(startingFitness, Context.TabuwalkingStat);
630    }
631
632    protected double ProbabilityAccept(ISingleObjectiveSolutionScope<TSolution> scope, IList<Tuple<double, double>> data) {
633      if (double.IsNaN(scope.Fitness)) {
634        Evaluate(scope, CancellationToken.None);
635        Context.IncrementEvaluatedSolutions(1);
636      }
637      return ProbabilityAccept(scope.Fitness, data);
638    }
639    protected double ProbabilityAccept(double startingFitness, IList<Tuple<double, double>> data) {
640      if (data.Count < 10) return 1.0;
641      int[] clusterValues;
642      var centroids = CkMeans1D.Cluster(data.Select(x => x.Item1).ToArray(), 2, out clusterValues);
643      var cluster = Math.Abs(startingFitness - centroids.First().Key) < Math.Abs(startingFitness - centroids.Last().Key) ? centroids.First().Value : centroids.Last().Value;
644
645      var samples = 0;
646      double meanStart = 0, meanStartOld = 0, meanEnd = 0, meanEndOld = 0;
647      double varStart = 0, varStartOld = 0, varEnd = 0, varEndOld = 0;
648      for (var i = 0; i < data.Count; i++) {
649        if (clusterValues[i] != cluster) continue;
650
651        samples++;
652        var x = data[i].Item1;
653        var y = data[i].Item2;
654
655        if (samples == 1) {
656          meanStartOld = x;
657          meanEndOld = y;
658        } else {
659          meanStart = meanStartOld + (x - meanStartOld) / samples;
660          meanEnd = meanEndOld + (x - meanEndOld) / samples;
661          varStart = varStartOld + (x - meanStartOld) * (x - meanStart) / (samples - 1);
662          varEnd = varEndOld + (x - meanEndOld) * (x - meanEnd) / (samples - 1);
663
664          meanStartOld = meanStart;
665          meanEndOld = meanEnd;
666          varStartOld = varStart;
667          varEndOld = varEnd;
668        }
669      }
670      if (samples < 5) return 1.0;
671      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;
672
673      var biasedMean = meanEnd + cov / varStart * (startingFitness - meanStart);
674      var biasedStdev = Math.Sqrt(varEnd - (cov * cov) / varStart);
675
676      if (Problem.Maximization) {
677        var goal = Context.Population.Min(x => x.Fitness);
678        var z = (goal - biasedMean) / biasedStdev;
679        return 1.0 - Phi(z); // P(X >= z)
680      } else {
681        var goal = Context.Population.Max(x => x.Fitness);
682        var z = (goal - biasedMean) / biasedStdev;
683        return Phi(z); // P(X <= z)
684      }
685    }
686
687    protected virtual bool Terminate() {
688      return MaximumEvaluations.HasValue && Context.EvaluatedSolutions >= MaximumEvaluations.Value
689        || MaximumExecutionTime.HasValue && ExecutionTime >= MaximumExecutionTime.Value
690        || TargetQuality.HasValue && (Problem.Maximization && Context.BestQuality >= TargetQuality.Value
691                                  || !Problem.Maximization && Context.BestQuality <= TargetQuality.Value);
692    }
693
694    public event PropertyChangedEventHandler PropertyChanged;
695    protected void OnPropertyChanged(string property) {
696      var handler = PropertyChanged;
697      if (handler != null) handler(this, new PropertyChangedEventArgs(property));
698    }
699
700    #region Engine Helper
701    protected void RunOperator(IOperator op, IScope scope, CancellationToken cancellationToken) {
702      var stack = new Stack<IOperation>();
703      stack.Push(Context.CreateChildOperation(op, scope));
704
705      while (stack.Count > 0) {
706        cancellationToken.ThrowIfCancellationRequested();
707
708        var next = stack.Pop();
709        if (next is OperationCollection) {
710          var coll = (OperationCollection)next;
711          for (int i = coll.Count - 1; i >= 0; i--)
712            if (coll[i] != null) stack.Push(coll[i]);
713        } else if (next is IAtomicOperation) {
714          var operation = (IAtomicOperation)next;
715          try {
716            next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
717          } catch (Exception ex) {
718            stack.Push(operation);
719            if (ex is OperationCanceledException) throw ex;
720            else throw new OperatorExecutionException(operation.Operator, ex);
721          }
722          if (next != null) stack.Push(next);
723        }
724      }
725    }
726    #endregion
727
728    #region Math Helper
729    // normal distribution CDF (left of x) for N(0;1) standard normal distribution
730    // from http://www.johndcook.com/blog/csharp_phi/
731    // license: "This code is in the public domain. Do whatever you want with it, no strings attached."
732    // added: 2016-11-19 21:46 CET
733    protected static double Phi(double x) {
734      // constants
735      double a1 = 0.254829592;
736      double a2 = -0.284496736;
737      double a3 = 1.421413741;
738      double a4 = -1.453152027;
739      double a5 = 1.061405429;
740      double p = 0.3275911;
741
742      // Save the sign of x
743      int sign = 1;
744      if (x < 0)
745        sign = -1;
746      x = Math.Abs(x) / Math.Sqrt(2.0);
747
748      // A&S formula 7.1.26
749      double t = 1.0 / (1.0 + p * x);
750      double y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * Math.Exp(-x * x);
751
752      return 0.5 * (1.0 + sign * y);
753    }
754    #endregion
755  }
756}
Note: See TracBrowser for help on using the repository browser.