Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2701:

  • Worked on MemPR algorithm for permutations
    • Made Evaluate() method mostly thread-safe and moved evaluated solutions counting to caller
  • Removed TSP specific similarity calculator (it is actually not specific to the TSP) and added it to the permutation encoding as HammingSimilarityCalculator
  • Fixed bug in qap basicproblem
File size: 33.1 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 (HillclimbingSuited(offspring))
560        HillClimb(offspring, token, subspace); // perform hillclimb in the solution sub-space
561      return offspring;
562    }
563
564    protected abstract ISingleObjectiveSolutionScope<TSolution> Cross(ISingleObjectiveSolutionScope<TSolution> p1, ISingleObjectiveSolutionScope<TSolution> p2, CancellationToken token);
565    protected abstract void Mutate(ISingleObjectiveSolutionScope<TSolution> offspring, CancellationToken token, ISolutionSubspace<TSolution> subspace = null);
566    #endregion
567
568    #region Relink
569    protected virtual ISingleObjectiveSolutionScope<TSolution> PerformRelinking(CancellationToken token) {
570      if (Context.PopulationCount < 2) throw new InvalidOperationException("Cannot breed from population with less than 2 individuals.");
571      var i1 = Context.Random.Next(Context.PopulationCount);
572      var i2 = Context.Random.Next(Context.PopulationCount);
573      while (i1 == i2) i2 = Context.Random.Next(Context.PopulationCount);
574
575      var p1 = Context.AtPopulation(i1);
576      var p2 = Context.AtPopulation(i2);
577
578      return RelinkAndImprove(p1, p2, token);
579    }
580
581    protected virtual ISingleObjectiveSolutionScope<TSolution> RelinkAndImprove(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b, CancellationToken token) {
582      var child = Relink(a, b, token);
583      if (IsBetter(child, a) && IsBetter(child, b)) return child;
584
585      var dist1 = Dist(child, a);
586      var dist2 = Dist(child, b);
587      if (dist1 > 0 && dist2 > 0) {
588        var subspace = CalculateSubspace(new[] { a.Solution, b.Solution }, inverse: true);
589        if (HillclimbingSuited(child)) {
590          HillClimb(child, token, subspace);
591        }
592      }
593      return child;
594    }
595
596    protected abstract ISingleObjectiveSolutionScope<TSolution> Relink(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b, CancellationToken token);
597    #endregion
598
599    #region Sample
600    protected virtual ISingleObjectiveSolutionScope<TSolution> PerformSampling(CancellationToken token) {
601      SolutionModelTrainerParameter.Value.TrainModel(Context);
602      var sample = ToScope(Context.Model.Sample());
603      Evaluate(sample, token);
604      Context.IncrementEvaluatedSolutions(1);
605      if (Context.Population.Any(p => IsBetter(sample, p) || sample.Fitness == p.Fitness)) return sample;
606
607      if (HillclimbingSuited(sample)) {
608        var subspace = CalculateSubspace(Context.Population.Select(x => x.Solution));
609        HillClimb(sample, token, subspace);
610      }
611      return sample;
612    }
613    #endregion
614
615    protected bool HillclimbingSuited(ISingleObjectiveSolutionScope<TSolution> scope) {
616      return Context.Random.NextDouble() < ProbabilityAccept(scope, Context.HillclimbingStat);
617    }
618    protected bool HillclimbingSuited(double startingFitness) {
619      return Context.Random.NextDouble() < ProbabilityAccept(startingFitness, Context.HillclimbingStat);
620    }
621    protected bool TabuwalkingSuited(ISingleObjectiveSolutionScope<TSolution> scope) {
622      return Context.Random.NextDouble() < ProbabilityAccept(scope, Context.TabuwalkingStat);
623    }
624    protected bool TabuwalkingSuited(double startingFitness) {
625      return Context.Random.NextDouble() < ProbabilityAccept(startingFitness, Context.TabuwalkingStat);
626    }
627
628    protected double ProbabilityAccept(ISingleObjectiveSolutionScope<TSolution> scope, IList<Tuple<double, double>> data) {
629      if (double.IsNaN(scope.Fitness)) {
630        Evaluate(scope, CancellationToken.None);
631        Context.IncrementEvaluatedSolutions(1);
632      }
633      return ProbabilityAccept(scope.Fitness, data);
634    }
635    protected double ProbabilityAccept(double startingFitness, IList<Tuple<double, double>> data) {
636      if (data.Count < 10) return 1.0;
637      int[] clusterValues;
638      var centroids = CkMeans1D.Cluster(data.Select(x => x.Item1).ToArray(), 2, out clusterValues);
639      var cluster = Math.Abs(startingFitness - centroids.First().Key) < Math.Abs(startingFitness - centroids.Last().Key) ? centroids.First().Value : centroids.Last().Value;
640
641      var samples = 0;
642      double meanStart = 0, meanStartOld = 0, meanEnd = 0, meanEndOld = 0;
643      double varStart = 0, varStartOld = 0, varEnd = 0, varEndOld = 0;
644      for (var i = 0; i < data.Count; i++) {
645        if (clusterValues[i] != cluster) continue;
646
647        samples++;
648        var x = data[i].Item1;
649        var y = data[i].Item2;
650
651        if (samples == 1) {
652          meanStartOld = x;
653          meanEndOld = y;
654        } else {
655          meanStart = meanStartOld + (x - meanStartOld) / samples;
656          meanEnd = meanEndOld + (x - meanEndOld) / samples;
657          varStart = varStartOld + (x - meanStartOld) * (x - meanStart) / (samples - 1);
658          varEnd = varEndOld + (x - meanEndOld) * (x - meanEnd) / (samples - 1);
659
660          meanStartOld = meanStart;
661          meanEndOld = meanEnd;
662          varStartOld = varStart;
663          varEndOld = varEnd;
664        }
665      }
666      if (samples < 5) return 1.0;
667      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;
668
669      var biasedMean = meanEnd + cov / varStart * (startingFitness - meanStart);
670      var biasedStdev = Math.Sqrt(varEnd - (cov * cov) / varStart);
671
672      if (Problem.Maximization) {
673        var goal = Context.Population.Min(x => x.Fitness);
674        var z = (goal - biasedMean) / biasedStdev;
675        return 1.0 - Phi(z); // P(X >= z)
676      } else {
677        var goal = Context.Population.Max(x => x.Fitness);
678        var z = (goal - biasedMean) / biasedStdev;
679        return Phi(z); // P(X <= z)
680      }
681    }
682
683    protected virtual bool Terminate() {
684      return MaximumEvaluations.HasValue && Context.EvaluatedSolutions >= MaximumEvaluations.Value
685        || MaximumExecutionTime.HasValue && ExecutionTime >= MaximumExecutionTime.Value
686        || TargetQuality.HasValue && (Problem.Maximization && Context.BestQuality >= TargetQuality.Value
687                                  || !Problem.Maximization && Context.BestQuality <= TargetQuality.Value);
688    }
689
690    public event PropertyChangedEventHandler PropertyChanged;
691    protected void OnPropertyChanged(string property) {
692      var handler = PropertyChanged;
693      if (handler != null) handler(this, new PropertyChangedEventArgs(property));
694    }
695
696    #region Engine Helper
697    protected void RunOperator(IOperator op, IScope scope, CancellationToken cancellationToken) {
698      var stack = new Stack<IOperation>();
699      stack.Push(Context.CreateChildOperation(op, scope));
700
701      while (stack.Count > 0) {
702        cancellationToken.ThrowIfCancellationRequested();
703
704        var next = stack.Pop();
705        if (next is OperationCollection) {
706          var coll = (OperationCollection)next;
707          for (int i = coll.Count - 1; i >= 0; i--)
708            if (coll[i] != null) stack.Push(coll[i]);
709        } else if (next is IAtomicOperation) {
710          var operation = (IAtomicOperation)next;
711          try {
712            next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
713          } catch (Exception ex) {
714            stack.Push(operation);
715            if (ex is OperationCanceledException) throw ex;
716            else throw new OperatorExecutionException(operation.Operator, ex);
717          }
718          if (next != null) stack.Push(next);
719        }
720      }
721    }
722    #endregion
723
724    #region Math Helper
725    // normal distribution CDF (left of x) for N(0;1) standard normal distribution
726    // from http://www.johndcook.com/blog/csharp_phi/
727    // license: "This code is in the public domain. Do whatever you want with it, no strings attached."
728    // added: 2016-11-19 21:46 CET
729    protected static double Phi(double x) {
730      // constants
731      double a1 = 0.254829592;
732      double a2 = -0.284496736;
733      double a3 = 1.421413741;
734      double a4 = -1.453152027;
735      double a5 = 1.061405429;
736      double p = 0.3275911;
737
738      // Save the sign of x
739      int sign = 1;
740      if (x < 0)
741        sign = -1;
742      x = Math.Abs(x) / Math.Sqrt(2.0);
743
744      // A&S formula 7.1.26
745      double t = 1.0 / (1.0 + p * x);
746      double y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * Math.Exp(-x * x);
747
748      return 0.5 * (1.0 + sign * y);
749    }
750    #endregion
751  }
752}
Note: See TracBrowser for help on using the repository browser.