Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2701: working on MemPR implementation

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