Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2701:

  • changed adaptive walk performance model to relative
  • added ConfidenceConstantModel for regression
  • using constant model as fallback to GPR
  • reorganized code
File size: 35.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.Linq;
25using System.Runtime.CompilerServices;
26using System.Threading;
27using HeuristicLab.Algorithms.DataAnalysis;
28using HeuristicLab.Algorithms.MemPR.Interfaces;
29using HeuristicLab.Analysis;
30using HeuristicLab.Common;
31using HeuristicLab.Core;
32using HeuristicLab.Data;
33using HeuristicLab.Optimization;
34using HeuristicLab.Parameters;
35using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
36using HeuristicLab.Problems.DataAnalysis;
37using HeuristicLab.Random;
38using ExecutionContext = HeuristicLab.Core.ExecutionContext;
39
40namespace HeuristicLab.Algorithms.MemPR {
41  [Item("MemPRContext", "Abstract base class for MemPR contexts.")]
42  [StorableClass]
43  public abstract class MemPRPopulationContext<TProblem, TSolution, TPopulationContext, TSolutionContext> : ParameterizedNamedItem,
44    IPopulationBasedHeuristicAlgorithmContext<TProblem, TSolution>, ISolutionModelContext<TSolution>, IEvaluationServiceContext<TSolution>
45      where TProblem : class, IItem, ISingleObjectiveHeuristicOptimizationProblem
46      where TSolution : class, IItem
47      where TPopulationContext : MemPRPopulationContext<TProblem, TSolution, TPopulationContext, TSolutionContext>
48      where TSolutionContext : MemPRSolutionContext<TProblem, TSolution, TPopulationContext, TSolutionContext> {
49
50    private IExecutionContext parent;
51    public IExecutionContext Parent {
52      get { return parent; }
53      set { parent = value; }
54    }
55
56    [Storable]
57    private IScope scope;
58    public IScope Scope {
59      get { return scope; }
60      private set { scope = value; }
61    }
62
63    IKeyedItemCollection<string, IParameter> IExecutionContext.Parameters {
64      get { return Parameters; }
65    }
66
67    [Storable]
68    private IValueParameter<TProblem> problem;
69    public TProblem Problem {
70      get { return problem.Value; }
71      set { problem.Value = value; }
72    }
73    public bool Maximization {
74      get { return ((IValueParameter<BoolValue>)Problem.MaximizationParameter).Value.Value; }
75    }
76
77    [Storable]
78    private IValueParameter<BoolValue> initialized;
79    public bool Initialized {
80      get { return initialized.Value.Value; }
81      set { initialized.Value.Value = value; }
82    }
83
84    [Storable]
85    private IValueParameter<IntValue> iterations;
86    public int Iterations {
87      get { return iterations.Value.Value; }
88      set { iterations.Value.Value = value; }
89    }
90
91    [Storable]
92    private IValueParameter<IntValue> evaluatedSolutions;
93    public int EvaluatedSolutions {
94      get { return evaluatedSolutions.Value.Value; }
95      set { evaluatedSolutions.Value.Value = value; }
96    }
97
98    [Storable]
99    private IValueParameter<DoubleValue> bestQuality;
100    public double BestQuality {
101      get { return bestQuality.Value.Value; }
102      set { bestQuality.Value.Value = value; }
103    }
104
105    [Storable]
106    private IValueParameter<TSolution> bestSolution;
107    public TSolution BestSolution {
108      get { return bestSolution.Value; }
109      set { bestSolution.Value = value; }
110    }
111
112    [Storable]
113    private IValueParameter<IntValue> localSearchEvaluations;
114    public int LocalSearchEvaluations {
115      get { return localSearchEvaluations.Value.Value; }
116      set { localSearchEvaluations.Value.Value = value; }
117    }
118
119    [Storable]
120    private IValueParameter<DoubleValue> localOptimaLevel;
121    public double LocalOptimaLevel {
122      get { return localOptimaLevel.Value.Value; }
123      set { localOptimaLevel.Value.Value = value; }
124    }
125
126    [Storable]
127    private IValueParameter<IntValue> byBreeding;
128    public int ByBreeding {
129      get { return byBreeding.Value.Value; }
130      set { byBreeding.Value.Value = value; }
131    }
132
133    [Storable]
134    private IValueParameter<IntValue> byRelinking;
135    public int ByRelinking {
136      get { return byRelinking.Value.Value; }
137      set { byRelinking.Value.Value = value; }
138    }
139
140    [Storable]
141    private IValueParameter<IntValue> byDelinking;
142    public int ByDelinking {
143      get { return byDelinking.Value.Value; }
144      set { byDelinking.Value.Value = value; }
145    }
146
147    [Storable]
148    private IValueParameter<IntValue> bySampling;
149    public int BySampling {
150      get { return bySampling.Value.Value; }
151      set { bySampling.Value.Value = value; }
152    }
153
154    [Storable]
155    private IValueParameter<IntValue> byHillclimbing;
156    public int ByHillclimbing {
157      get { return byHillclimbing.Value.Value; }
158      set { byHillclimbing.Value.Value = value; }
159    }
160
161    [Storable]
162    private IValueParameter<IntValue> byAdaptivewalking;
163    public int ByAdaptivewalking {
164      get { return byAdaptivewalking.Value.Value; }
165      set { byAdaptivewalking.Value.Value = value; }
166    }
167
168    [Storable]
169    private IValueParameter<IRandom> random;
170    public IRandom Random {
171      get { return random.Value; }
172      set { random.Value = value; }
173    }
174   
175    public IEnumerable<ISingleObjectiveSolutionScope<TSolution>> Population {
176      get { return scope.SubScopes.OfType<ISingleObjectiveSolutionScope<TSolution>>(); }
177    }
178    public void AddToPopulation(ISingleObjectiveSolutionScope<TSolution> solScope) {
179      scope.SubScopes.Add(solScope);
180    }
181    public void ReplaceAtPopulation(int index, ISingleObjectiveSolutionScope<TSolution> solScope) {
182      scope.SubScopes[index] = solScope;
183    }
184    public ISingleObjectiveSolutionScope<TSolution> AtPopulation(int index) {
185      return scope.SubScopes[index] as ISingleObjectiveSolutionScope<TSolution>;
186    }
187    public void SortPopulation() {
188      scope.SubScopes.Replace(scope.SubScopes.OfType<ISingleObjectiveSolutionScope<TSolution>>().OrderBy(x => Maximization ? -x.Fitness : x.Fitness).ToList());
189    }
190    public int PopulationCount {
191      get { return scope.SubScopes.Count; }
192    }
193
194    [Storable]
195    private IConfidenceRegressionModel breedingPerformanceModel;
196    public IConfidenceRegressionModel BreedingPerformanceModel {
197      get { return breedingPerformanceModel; }
198    }
199    [Storable]
200    private List<Tuple<double, double, double, double>> breedingStat;
201    public IEnumerable<Tuple<double, double, double, double>> BreedingStat {
202      get { return breedingStat; }
203    }
204    [Storable]
205    private IConfidenceRegressionModel relinkingPerformanceModel;
206    public IConfidenceRegressionModel RelinkingPerformanceModel {
207      get { return relinkingPerformanceModel; }
208    }
209    [Storable]
210    private List<Tuple<double, double, double, double>> relinkingStat;
211    public IEnumerable<Tuple<double, double, double, double>> RelinkingStat {
212      get { return relinkingStat; }
213    }
214    [Storable]
215    private IConfidenceRegressionModel delinkingPerformanceModel;
216    public IConfidenceRegressionModel DelinkingPerformanceModel {
217      get { return delinkingPerformanceModel; }
218    }
219    [Storable]
220    private List<Tuple<double, double, double, double>> delinkingStat;
221    public IEnumerable<Tuple<double, double, double, double>> DelinkingStat {
222      get { return delinkingStat; }
223    }
224    [Storable]
225    private IConfidenceRegressionModel samplingPerformanceModel;
226    public IConfidenceRegressionModel SamplingPerformanceModel {
227      get { return samplingPerformanceModel; }
228    }
229    [Storable]
230    private List<Tuple<double, double>> samplingStat;
231    public IEnumerable<Tuple<double, double>> SamplingStat {
232      get { return samplingStat; }
233    }
234    [Storable]
235    private IConfidenceRegressionModel hillclimbingPerformanceModel;
236    public IConfidenceRegressionModel HillclimbingPerformanceModel {
237      get { return hillclimbingPerformanceModel; }
238    }
239    [Storable]
240    private List<Tuple<double, double>> hillclimbingStat;
241    public IEnumerable<Tuple<double, double>> HillclimbingStat {
242      get { return hillclimbingStat; }
243    }
244    [Storable]
245    private IConfidenceRegressionModel adaptiveWalkPerformanceModel;
246    public IConfidenceRegressionModel AdaptiveWalkPerformanceModel {
247      get { return adaptiveWalkPerformanceModel; }
248    }
249    [Storable]
250    private List<Tuple<double, double>> adaptivewalkingStat;
251    public IEnumerable<Tuple<double, double>> AdaptivewalkingStat {
252      get { return adaptivewalkingStat; }
253    }
254
255    [Storable]
256    public ISolutionModel<TSolution> Model { get; set; }
257
258    [StorableConstructor]
259    protected MemPRPopulationContext(bool deserializing) : base(deserializing) { }
260    protected MemPRPopulationContext(MemPRPopulationContext<TProblem, TSolution, TPopulationContext, TSolutionContext> original, Cloner cloner)
261      : base(original, cloner) {
262      scope = cloner.Clone(original.scope);
263      problem = cloner.Clone(original.problem);
264      initialized = cloner.Clone(original.initialized);
265      iterations = cloner.Clone(original.iterations);
266      evaluatedSolutions = cloner.Clone(original.evaluatedSolutions);
267      bestQuality = cloner.Clone(original.bestQuality);
268      bestSolution = cloner.Clone(original.bestSolution);
269      localSearchEvaluations = cloner.Clone(original.localSearchEvaluations);
270      localOptimaLevel = cloner.Clone(original.localOptimaLevel);
271      byBreeding = cloner.Clone(original.byBreeding);
272      byRelinking = cloner.Clone(original.byRelinking);
273      byDelinking = cloner.Clone(original.byDelinking);
274      bySampling = cloner.Clone(original.bySampling);
275      byHillclimbing = cloner.Clone(original.byHillclimbing);
276      byAdaptivewalking = cloner.Clone(original.byAdaptivewalking);
277      random = cloner.Clone(original.random);
278      breedingPerformanceModel = cloner.Clone(original.breedingPerformanceModel);
279      breedingStat = original.breedingStat.Select(x => Tuple.Create(x.Item1, x.Item2, x.Item3, x.Item4)).ToList();
280      relinkingPerformanceModel = cloner.Clone(original.relinkingPerformanceModel);
281      relinkingStat = original.relinkingStat.Select(x => Tuple.Create(x.Item1, x.Item2, x.Item3, x.Item4)).ToList();
282      delinkingPerformanceModel = cloner.Clone(original.delinkingPerformanceModel);
283      delinkingStat = original.delinkingStat.Select(x => Tuple.Create(x.Item1, x.Item2, x.Item3, x.Item4)).ToList();
284      samplingPerformanceModel = cloner.Clone(original.samplingPerformanceModel);
285      samplingStat = original.samplingStat.Select(x => Tuple.Create(x.Item1, x.Item2)).ToList();
286      hillclimbingPerformanceModel = cloner.Clone(original.hillclimbingPerformanceModel);
287      hillclimbingStat = original.hillclimbingStat.Select(x => Tuple.Create(x.Item1, x.Item2)).ToList();
288      adaptiveWalkPerformanceModel = cloner.Clone(original.adaptiveWalkPerformanceModel);
289      adaptivewalkingStat = original.adaptivewalkingStat.Select(x => Tuple.Create(x.Item1, x.Item2)).ToList();
290     
291      Model = cloner.Clone(original.Model);
292    }
293    public MemPRPopulationContext() : this("MemPRContext") { }
294    public MemPRPopulationContext(string name) : base(name) {
295      scope = new Scope("Global");
296
297      Parameters.Add(problem = new ValueParameter<TProblem>("Problem"));
298      Parameters.Add(initialized = new ValueParameter<BoolValue>("Initialized", new BoolValue(false)));
299      Parameters.Add(iterations = new ValueParameter<IntValue>("Iterations", new IntValue(0)));
300      Parameters.Add(evaluatedSolutions = new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue(0)));
301      Parameters.Add(bestQuality = new ValueParameter<DoubleValue>("BestQuality", new DoubleValue(double.NaN)));
302      Parameters.Add(bestSolution = new ValueParameter<TSolution>("BestFoundSolution"));
303      Parameters.Add(localSearchEvaluations = new ValueParameter<IntValue>("LocalSearchEvaluations", new IntValue(0)));
304      Parameters.Add(localOptimaLevel = new ValueParameter<DoubleValue>("LocalOptimaLevel", new DoubleValue(0)));
305      Parameters.Add(byBreeding = new ValueParameter<IntValue>("ByBreeding", new IntValue(0)));
306      Parameters.Add(byRelinking = new ValueParameter<IntValue>("ByRelinking", new IntValue(0)));
307      Parameters.Add(byDelinking = new ValueParameter<IntValue>("ByDelinking", new IntValue(0)));
308      Parameters.Add(bySampling = new ValueParameter<IntValue>("BySampling", new IntValue(0)));
309      Parameters.Add(byHillclimbing = new ValueParameter<IntValue>("ByHillclimbing", new IntValue(0)));
310      Parameters.Add(byAdaptivewalking = new ValueParameter<IntValue>("ByAdaptivewalking", new IntValue(0)));
311      Parameters.Add(random = new ValueParameter<IRandom>("Random", new MersenneTwister()));
312
313      breedingStat = new List<Tuple<double, double, double, double>>();
314      relinkingStat = new List<Tuple<double, double, double, double>>();
315      delinkingStat = new List<Tuple<double, double, double, double>>();
316      samplingStat = new List<Tuple<double, double>>();
317      hillclimbingStat = new List<Tuple<double, double>>();
318      adaptivewalkingStat = new List<Tuple<double, double>>();
319    }
320
321    public abstract ISingleObjectiveSolutionScope<TSolution> ToScope(TSolution code, double fitness = double.NaN);
322
323    public virtual double Evaluate(TSolution solution, CancellationToken token) {
324      var solScope = ToScope(solution);
325      Evaluate(solScope, token);
326      return solScope.Fitness;
327    }
328
329    public virtual void Evaluate(ISingleObjectiveSolutionScope<TSolution> solScope, CancellationToken token) {
330      var pdef = Problem as ISingleObjectiveProblemDefinition;
331      if (pdef != null) {
332        var ind = new SingleEncodingIndividual(pdef.Encoding, solScope);
333        solScope.Fitness = pdef.Evaluate(ind, Random);
334      } else {
335        RunOperator(Problem.Evaluator, solScope, token);
336      }
337    }
338
339    public abstract TSolutionContext CreateSingleSolutionContext(ISingleObjectiveSolutionScope<TSolution> solution);
340
341    public void IncrementEvaluatedSolutions(int byEvaluations) {
342      if (byEvaluations < 0) throw new ArgumentException("Can only increment and not decrement evaluated solutions.");
343      EvaluatedSolutions += byEvaluations;
344    }
345
346    #region Breeding Performance
347    public void AddBreedingResult(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b, double parentDist, ISingleObjectiveSolutionScope<TSolution> child) {
348      if (IsBetter(a, b))
349        breedingStat.Add(Tuple.Create(a.Fitness, b.Fitness, parentDist, child.Fitness));
350      else breedingStat.Add(Tuple.Create(b.Fitness, a.Fitness, parentDist, child.Fitness));
351      if (breedingStat.Count % 10 == 0) RelearnBreedingPerformanceModel();
352    }
353    public void RelearnBreedingPerformanceModel() {
354      breedingPerformanceModel = RunRegression(PrepareRegression(ToListRow(breedingStat)), breedingPerformanceModel).Model;
355    }
356    public bool BreedingSuited(ISingleObjectiveSolutionScope<TSolution> p1, ISingleObjectiveSolutionScope<TSolution> p2, double dist) {
357      if (breedingPerformanceModel == null) return true;
358      double minI1 = double.MaxValue, minI2 = double.MaxValue, maxI1 = double.MinValue, maxI2 = double.MinValue;
359      foreach (var d in BreedingStat) {
360        if (d.Item1 < minI1) minI1 = d.Item1;
361        if (d.Item1 > maxI1) maxI1 = d.Item1;
362        if (d.Item2 < minI2) minI2 = d.Item2;
363        if (d.Item2 > maxI2) maxI2 = d.Item2;
364      }
365      if (p1.Fitness < minI1 || p1.Fitness > maxI1 || p2.Fitness < minI2 || p2.Fitness > maxI2)
366        return true;
367     
368      return Random.NextDouble() < ProbabilityAcceptAbsolutePerformanceModel(new List<double> { p1.Fitness, p2.Fitness, dist }, breedingPerformanceModel);
369    }
370    #endregion
371
372    #region Relinking Performance
373    public void AddRelinkingResult(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b, double parentDist, ISingleObjectiveSolutionScope<TSolution> child) {
374      if (IsBetter(a, b))
375        relinkingStat.Add(Tuple.Create(a.Fitness, b.Fitness, parentDist, Maximization ? child.Fitness - a.Fitness : a.Fitness - child.Fitness));
376      else relinkingStat.Add(Tuple.Create(a.Fitness, b.Fitness, parentDist, Maximization ? child.Fitness - b.Fitness : b.Fitness - child.Fitness));
377      if (relinkingStat.Count % 10 == 0) RelearnRelinkingPerformanceModel();
378    }
379    public void RelearnRelinkingPerformanceModel() {
380      relinkingPerformanceModel = RunRegression(PrepareRegression(ToListRow(relinkingStat)), relinkingPerformanceModel).Model;
381    }
382    public bool RelinkSuited(ISingleObjectiveSolutionScope<TSolution> p1, ISingleObjectiveSolutionScope<TSolution> p2, double dist) {
383      if (relinkingPerformanceModel == null) return true;
384      double minI1 = double.MaxValue, minI2 = double.MaxValue, maxI1 = double.MinValue, maxI2 = double.MinValue;
385      foreach (var d in RelinkingStat) {
386        if (d.Item1 < minI1) minI1 = d.Item1;
387        if (d.Item1 > maxI1) maxI1 = d.Item1;
388        if (d.Item2 < minI2) minI2 = d.Item2;
389        if (d.Item2 > maxI2) maxI2 = d.Item2;
390      }
391      if (p1.Fitness < minI1 || p1.Fitness > maxI1 || p2.Fitness < minI2 || p2.Fitness > maxI2)
392        return true;
393
394      if (IsBetter(p1, p2)) {
395        return Random.NextDouble() < ProbabilityAcceptRelativePerformanceModel(p1.Fitness, new List<double> { p1.Fitness, p2.Fitness, dist }, relinkingPerformanceModel);
396      }
397      return Random.NextDouble() < ProbabilityAcceptRelativePerformanceModel(p2.Fitness, new List<double> { p1.Fitness, p2.Fitness, dist }, relinkingPerformanceModel);
398    }
399    #endregion
400
401    #region Delinking Performance
402    public void AddDelinkingResult(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b, double parentDist, ISingleObjectiveSolutionScope<TSolution> child) {
403      if (IsBetter(a, b))
404        delinkingStat.Add(Tuple.Create(a.Fitness, b.Fitness, parentDist, Maximization ? child.Fitness - a.Fitness : a.Fitness - child.Fitness));
405      else delinkingStat.Add(Tuple.Create(a.Fitness, b.Fitness, parentDist, Maximization ? child.Fitness - b.Fitness : b.Fitness - child.Fitness));
406      if (delinkingStat.Count % 10 == 0) RelearnDelinkingPerformanceModel();
407    }
408    public void RelearnDelinkingPerformanceModel() {
409      delinkingPerformanceModel = RunRegression(PrepareRegression(ToListRow(delinkingStat)), delinkingPerformanceModel).Model;
410    }
411    public bool DelinkSuited(ISingleObjectiveSolutionScope<TSolution> p1, ISingleObjectiveSolutionScope<TSolution> p2, double dist) {
412      if (delinkingPerformanceModel == null) return true;
413      double minI1 = double.MaxValue, minI2 = double.MaxValue, maxI1 = double.MinValue, maxI2 = double.MinValue;
414      foreach (var d in DelinkingStat) {
415        if (d.Item1 < minI1) minI1 = d.Item1;
416        if (d.Item1 > maxI1) maxI1 = d.Item1;
417        if (d.Item2 < minI2) minI2 = d.Item2;
418        if (d.Item2 > maxI2) maxI2 = d.Item2;
419      }
420      if (p1.Fitness < minI1 || p1.Fitness > maxI1 || p2.Fitness < minI2 || p2.Fitness > maxI2)
421        return true;
422      if (IsBetter(p1, p2)) {
423        return Random.NextDouble() < ProbabilityAcceptRelativePerformanceModel(p1.Fitness, new List<double> { p1.Fitness, p2.Fitness, dist }, delinkingPerformanceModel);
424      }
425      return Random.NextDouble() < ProbabilityAcceptRelativePerformanceModel(p2.Fitness, new List<double> { p1.Fitness, p2.Fitness, dist }, delinkingPerformanceModel);
426    }
427    #endregion
428
429    #region Sampling Performance
430    public void AddSamplingResult(ISingleObjectiveSolutionScope<TSolution> sample, double avgDist) {
431      samplingStat.Add(Tuple.Create(avgDist, sample.Fitness));
432      if (samplingStat.Count % 10 == 0) RelearnSamplingPerformanceModel();
433    }
434    public void RelearnSamplingPerformanceModel() {
435      samplingPerformanceModel = RunRegression(PrepareRegression(ToListRow(samplingStat)), samplingPerformanceModel).Model;
436    }
437    public bool SamplingSuited(double avgDist) {
438      if (samplingPerformanceModel == null) return true;
439      if (avgDist < samplingStat.Min(x => x.Item1) || avgDist > samplingStat.Max(x => x.Item1)) return true;
440      return Random.NextDouble() < ProbabilityAcceptAbsolutePerformanceModel(new List<double> { avgDist }, samplingPerformanceModel);
441    }
442    #endregion
443
444    #region Hillclimbing Performance
445    public void AddHillclimbingResult(ISingleObjectiveSolutionScope<TSolution> input, ISingleObjectiveSolutionScope<TSolution> outcome) {
446      hillclimbingStat.Add(Tuple.Create(input.Fitness, Maximization ? outcome.Fitness - input.Fitness : input.Fitness - outcome.Fitness));
447      if (hillclimbingStat.Count % 10 == 0) RelearnHillclimbingPerformanceModel();
448    }
449    public void RelearnHillclimbingPerformanceModel() {
450      hillclimbingPerformanceModel = RunRegression(PrepareRegression(ToListRow(hillclimbingStat)), hillclimbingPerformanceModel).Model;
451    }
452    public bool HillclimbingSuited(double startingFitness) {
453      if (hillclimbingPerformanceModel == null) return true;
454      if (startingFitness < HillclimbingStat.Min(x => x.Item1) || startingFitness > HillclimbingStat.Max(x => x.Item1))
455        return true;
456      return Random.NextDouble() < ProbabilityAcceptRelativePerformanceModel(startingFitness, new List<double> { startingFitness }, hillclimbingPerformanceModel);
457    }
458    #endregion
459
460    #region Adaptivewalking Performance
461    public void AddAdaptivewalkingResult(ISingleObjectiveSolutionScope<TSolution> input, ISingleObjectiveSolutionScope<TSolution> outcome) {
462      adaptivewalkingStat.Add(Tuple.Create(input.Fitness, Maximization ? outcome.Fitness - input.Fitness : input.Fitness - outcome.Fitness));
463      if (adaptivewalkingStat.Count % 10 == 0) RelearnAdaptiveWalkPerformanceModel();
464    }
465    public void RelearnAdaptiveWalkPerformanceModel() {
466      adaptiveWalkPerformanceModel = RunRegression(PrepareRegression(ToListRow(adaptivewalkingStat)), adaptiveWalkPerformanceModel).Model;
467    }
468    public bool AdaptivewalkingSuited(double startingFitness) {
469      if (adaptiveWalkPerformanceModel == null) return true;
470      if (startingFitness < AdaptivewalkingStat.Min(x => x.Item1) || startingFitness > AdaptivewalkingStat.Max(x => x.Item1))
471        return true;
472      return Random.NextDouble() < ProbabilityAcceptRelativePerformanceModel(startingFitness, new List<double> { startingFitness }, adaptiveWalkPerformanceModel);
473    }
474    #endregion
475
476    public IConfidenceRegressionSolution GetSolution(IConfidenceRegressionModel model, IEnumerable<Tuple<double, double>> data) {
477      return new ConfidenceRegressionSolution(model, PrepareRegression(ToListRow(data.ToList())));
478    }
479    public IConfidenceRegressionSolution GetSolution(IConfidenceRegressionModel model, IEnumerable<Tuple<double, double, double>> data) {
480      return new ConfidenceRegressionSolution(model, PrepareRegression(ToListRow(data.ToList())));
481    }
482    public IConfidenceRegressionSolution GetSolution(IConfidenceRegressionModel model, IEnumerable<Tuple<double, double, double, double>> data) {
483      return new ConfidenceRegressionSolution(model, PrepareRegression(ToListRow(data.ToList())));
484    }
485
486    protected RegressionProblemData PrepareRegression(List<List<double>> data) {
487      var columns = data.First().Select(y => new List<double>()).ToList();
488      foreach (var next in data.Shuffle(Random)) {
489        for (var i = 0; i < next.Count; i++) {
490          columns[i].Add(next[i]);
491        }
492      }
493      var ds = new Dataset(columns.Select((v, i) => i < columns.Count - 1 ? "in" + i : "out").ToList(), columns);
494      var regPrb = new RegressionProblemData(ds, Enumerable.Range(0, columns.Count - 1).Select(x => "in" + x), "out") {
495        TrainingPartition = { Start = 0, End = Math.Min(50, data.Count) },
496        TestPartition = { Start = Math.Min(50, data.Count), End = data.Count }
497      };
498      return regPrb;
499    }
500
501    protected static IConfidenceRegressionSolution RunRegression(RegressionProblemData trainingData, IConfidenceRegressionModel baseLineModel = null) {
502      var targetValues = trainingData.Dataset.GetDoubleValues(trainingData.TargetVariable, trainingData.TrainingIndices).ToList();
503      var baseline = baseLineModel != null ? new ConfidenceRegressionSolution(baseLineModel, trainingData) : null;
504      var constantSolution = new ConfidenceRegressionSolution(new ConfidenceConstantModel(targetValues.Average(), targetValues.Variance(), trainingData.TargetVariable), trainingData);
505      var gpr = new GaussianProcessRegression { Problem = { ProblemData = trainingData } };
506      if (trainingData.InputVariables.CheckedItems.Any(x => alglib.pearsoncorr2(trainingData.Dataset.GetDoubleValues(x.Value.Value).ToArray(), trainingData.TargetVariableValues.ToArray()) > 0.8)) {
507        gpr.MeanFunction = new MeanZero();
508        var cov1 = new CovarianceSum();
509        cov1.Terms.Add(new CovarianceLinearArd());
510        cov1.Terms.Add(new CovarianceConst());
511        gpr.CovarianceFunction = cov1;
512      }
513      IConfidenceRegressionSolution solution = null;
514      var cnt = 0;
515      do {
516        ExecuteAlgorithm(gpr);
517        solution = (IConfidenceRegressionSolution)gpr.Results["Solution"].Value;
518        cnt++;
519      } while (cnt < 10 && (solution == null || solution.TrainingRSquared.IsAlmost(0)));
520
521      return GetBestRegressionSolution(constantSolution, baseline, solution);
522    }
523
524    private static IConfidenceRegressionSolution GetBestRegressionSolution(IConfidenceRegressionSolution constant, IConfidenceRegressionSolution baseline, IConfidenceRegressionSolution solution) {
525      if (baseline == null)
526        return constant.TrainingMeanAbsoluteError < solution.TrainingMeanAbsoluteError ? constant : solution;
527
528      double a, b, c;
529      if (constant.ProblemData.Dataset.Rows < 60) {
530        c = constant.TrainingMeanAbsoluteError;
531        b = baseline.TrainingMeanAbsoluteError;
532        a = solution.TrainingMeanAbsoluteError;
533      } else {
534        c = constant.TestMeanAbsoluteError;
535        b = baseline.TestMeanAbsoluteError;
536        a = solution.TestMeanAbsoluteError;
537      }
538      if (c < b && (c < a || b < a)) return constant;
539      if (b < c && (b < a || c < a)) return baseline;
540      return solution;
541    }
542
543    protected static void ExecuteAlgorithm(IAlgorithm algorithm) {
544      using (var evt = new AutoResetEvent(false)) {
545        EventHandler exeStateChanged = (o, args) => {
546          if (algorithm.ExecutionState != ExecutionState.Started)
547            evt.Set();
548        };
549        algorithm.ExecutionStateChanged += exeStateChanged;
550        if (algorithm.ExecutionState != ExecutionState.Prepared) {
551          algorithm.Prepare(true);
552          evt.WaitOne();
553        }
554        algorithm.Start();
555        evt.WaitOne();
556        algorithm.ExecutionStateChanged -= exeStateChanged;
557      }
558    }
559
560    private double ProbabilityAcceptAbsolutePerformanceModel(List<double> inputs, IConfidenceRegressionModel model) {
561      var inputVariables = inputs.Select((v, i) => "in" + i);
562      var ds = new Dataset(inputVariables.Concat( new [] { "out" }), inputs.Select(x => new List<double> { x }).Concat(new [] { new List<double> { double.NaN } }));
563      var mean = model.GetEstimatedValues(ds, new[] { 0 }).Single();
564      var sdev = Math.Sqrt(model.GetEstimatedVariances(ds, new[] { 0 }).Single());
565
566      // calculate the fitness goal
567      var goal = Maximization ? Population.Min(x => x.Fitness) : Population.Max(x => x.Fitness);
568      var z = (goal - mean) / sdev;
569      // return the probability of achieving or surpassing that goal
570      var y = alglib.invnormaldistribution(z);
571      return Maximization ? 1.0 - y /* P(X >= z) */ : y; // P(X <= z)
572    }
573
574    private double ProbabilityAcceptRelativePerformanceModel(double basePerformance, List<double> inputs, IConfidenceRegressionModel model) {
575      var inputVariables = inputs.Select((v, i) => "in" + i);
576      var ds = new Dataset(inputVariables.Concat(new[] { "out" }), inputs.Select(x => new List<double> { x }).Concat(new[] { new List<double> { double.NaN } }));
577      var mean = model.GetEstimatedValues(ds, new[] { 0 }).Single();
578      var sdev = Math.Sqrt(model.GetEstimatedVariances(ds, new[] { 0 }).Single());
579
580      // calculate the improvement goal
581      var goal = Maximization ? Population.Min(x => x.Fitness) - basePerformance : basePerformance - Population.Max(x => x.Fitness);
582      var z = (goal - mean) / sdev;
583      // return the probability of achieving or surpassing that goal
584      return 1.0 - alglib.invnormaldistribution(z); /* P(X >= z) */
585    }
586
587    private static List<List<double>> ToListRow(List<Tuple<double, double>> rows) {
588      return rows.Select(x => new List<double> { x.Item1, x.Item2 }).ToList();
589    }
590    private static List<List<double>> ToListRow(List<Tuple<double, double, double>> rows) {
591      return rows.Select(x => new List<double> { x.Item1, x.Item2, x.Item3 }).ToList();
592    }
593    private static List<List<double>> ToListRow(List<Tuple<double, double, double, double>> rows) {
594      return rows.Select(x => new List<double> { x.Item1, x.Item2, x.Item3, x.Item4 }).ToList();
595    }
596
597    [MethodImpl(MethodImplOptions.AggressiveInlining)]
598    public bool IsBetter(ISingleObjectiveSolutionScope<TSolution> a, ISingleObjectiveSolutionScope<TSolution> b) {
599      return IsBetter(a.Fitness, b.Fitness);
600    }
601    [MethodImpl(MethodImplOptions.AggressiveInlining)]
602    public bool IsBetter(double a, double b) {
603      return double.IsNaN(b) && !double.IsNaN(a)
604        || Maximization && a > b
605        || !Maximization && a < b;
606    }
607
608    #region IExecutionContext members
609    public IAtomicOperation CreateOperation(IOperator op) {
610      return new ExecutionContext(this, op, Scope);
611    }
612
613    public IAtomicOperation CreateOperation(IOperator op, IScope s) {
614      return new ExecutionContext(this, op, s);
615    }
616
617    public IAtomicOperation CreateChildOperation(IOperator op) {
618      return new ExecutionContext(this, op, Scope);
619    }
620
621    public IAtomicOperation CreateChildOperation(IOperator op, IScope s) {
622      return new ExecutionContext(this, op, s);
623    }
624    #endregion
625
626    #region Engine Helper
627    public void RunOperator(IOperator op, IScope scope, CancellationToken cancellationToken) {
628      var stack = new Stack<IOperation>();
629      stack.Push(CreateChildOperation(op, scope));
630
631      while (stack.Count > 0) {
632        cancellationToken.ThrowIfCancellationRequested();
633
634        var next = stack.Pop();
635        if (next is OperationCollection) {
636          var coll = (OperationCollection)next;
637          for (int i = coll.Count - 1; i >= 0; i--)
638            if (coll[i] != null) stack.Push(coll[i]);
639        } else if (next is IAtomicOperation) {
640          var operation = (IAtomicOperation)next;
641          try {
642            next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
643          } catch (Exception ex) {
644            stack.Push(operation);
645            if (ex is OperationCanceledException) throw ex;
646            else throw new OperatorExecutionException(operation.Operator, ex);
647          }
648          if (next != null) stack.Push(next);
649        }
650      }
651    }
652    #endregion
653  }
654
655  [Item("SingleSolutionMemPRContext", "Abstract base class for single solution MemPR contexts.")]
656  [StorableClass]
657  public abstract class MemPRSolutionContext<TProblem, TSolution, TContext, TSolutionContext> : ParameterizedNamedItem,
658    ISingleSolutionHeuristicAlgorithmContext<TProblem, TSolution>, IEvaluationServiceContext<TSolution>
659      where TProblem : class, IItem, ISingleObjectiveHeuristicOptimizationProblem
660      where TSolution : class, IItem
661      where TContext : MemPRPopulationContext<TProblem, TSolution, TContext, TSolutionContext>
662      where TSolutionContext : MemPRSolutionContext<TProblem, TSolution, TContext, TSolutionContext> {
663
664    private TContext parent;
665    public IExecutionContext Parent {
666      get { return parent; }
667      set { throw new InvalidOperationException("Cannot set the parent of a single-solution context."); }
668    }
669
670    [Storable]
671    private ISingleObjectiveSolutionScope<TSolution> scope;
672    public IScope Scope {
673      get { return scope; }
674    }
675
676    IKeyedItemCollection<string, IParameter> IExecutionContext.Parameters {
677      get { return Parameters; }
678    }
679
680    public TProblem Problem {
681      get { return parent.Problem; }
682    }
683    public bool Maximization {
684      get { return parent.Maximization; }
685    }
686
687    public double BestQuality {
688      get { return parent.BestQuality; }
689      set { parent.BestQuality = value; }
690    }
691
692    public TSolution BestSolution {
693      get { return parent.BestSolution; }
694      set { parent.BestSolution = value; }
695    }
696
697    public IRandom Random {
698      get { return parent.Random; }
699    }
700
701    [Storable]
702    private IValueParameter<IntValue> evaluatedSolutions;
703    public int EvaluatedSolutions {
704      get { return evaluatedSolutions.Value.Value; }
705      set { evaluatedSolutions.Value.Value = value; }
706    }
707
708    [Storable]
709    private IValueParameter<IntValue> iterations;
710    public int Iterations {
711      get { return iterations.Value.Value; }
712      set { iterations.Value.Value = value; }
713    }
714
715    ISingleObjectiveSolutionScope<TSolution> ISingleSolutionHeuristicAlgorithmContext<TProblem, TSolution>.Solution {
716      get { return scope; }
717    }
718
719    [StorableConstructor]
720    protected MemPRSolutionContext(bool deserializing) : base(deserializing) { }
721    protected MemPRSolutionContext(MemPRSolutionContext<TProblem, TSolution, TContext, TSolutionContext> original, Cloner cloner)
722      : base(original, cloner) {
723      scope = cloner.Clone(original.scope);
724      evaluatedSolutions = cloner.Clone(original.evaluatedSolutions);
725      iterations = cloner.Clone(original.iterations);
726    }
727    public MemPRSolutionContext(TContext baseContext, ISingleObjectiveSolutionScope<TSolution> solution) {
728      parent = baseContext;
729      scope = solution;
730     
731      Parameters.Add(evaluatedSolutions = new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue(0)));
732      Parameters.Add(iterations = new ValueParameter<IntValue>("Iterations", new IntValue(0)));
733    }
734
735    public void IncrementEvaluatedSolutions(int byEvaluations) {
736      if (byEvaluations < 0) throw new ArgumentException("Can only increment and not decrement evaluated solutions.");
737      EvaluatedSolutions += byEvaluations;
738    }
739    public virtual double Evaluate(TSolution solution, CancellationToken token) {
740      return parent.Evaluate(solution, token);
741    }
742
743    public virtual void Evaluate(ISingleObjectiveSolutionScope<TSolution> solScope, CancellationToken token) {
744      parent.Evaluate(solScope, token);
745    }
746
747    #region IExecutionContext members
748    public IAtomicOperation CreateOperation(IOperator op) {
749      return new ExecutionContext(this, op, Scope);
750    }
751
752    public IAtomicOperation CreateOperation(IOperator op, IScope s) {
753      return new ExecutionContext(this, op, s);
754    }
755
756    public IAtomicOperation CreateChildOperation(IOperator op) {
757      return new ExecutionContext(this, op, Scope);
758    }
759
760    public IAtomicOperation CreateChildOperation(IOperator op, IScope s) {
761      return new ExecutionContext(this, op, s);
762    }
763    #endregion
764  }
765}
Note: See TracBrowser for help on using the repository browser.