Free cookie consent management tool by TermsFeed Policy Generator

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

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

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

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