Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PerformanceComparison/HeuristicLab.Analysis/3.3/Optimizers/IRRRun.cs @ 12803

Last change on this file since 12803 was 12803, checked in by abeham, 9 years ago

#2431: worked on RLD analysis

  • started implementation of IRRRun
  • renamed view from ECDF to RLD
  • reverted algorithms (execution time)
  • changed per clock analyzer
File size: 20.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Drawing;
26using System.Linq;
27using HeuristicLab.Common;
28using HeuristicLab.Common.Resources;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Optimization;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33
34namespace HeuristicLab.Analysis {
35  public enum TerminationCriterium { OnlyByTime, OnlyByEvaluations, OnlyByTarget, ByTargetAndTime, ByTargetAndEvaluations, WhicheverHitsFirst, WhicheverHitsLast }
36  /// <summary>
37  /// A run in which an algorithm is executed for a certain maximum time only.
38  /// </summary>
39  [Item("Independent Random Restart Run", "A run in which an optimizer is repeated until either a certain target value is reached or a maximum budget is exceeded.")]
40  [Creatable(CreatableAttribute.Categories.TestingAndAnalysis, Priority = 117)]
41  [StorableClass]
42  public sealed class IndepdentRandomRestartRun : NamedItem, IOptimizer, IStorableContent, INotifyPropertyChanged {
43    public string Filename { get; set; }
44
45    #region ItemImage
46    public static new Image StaticItemImage {
47      get { return VSImageLibrary.Event; }
48    }
49    public override Image ItemImage {
50      get { return (Algorithm != null) ? Algorithm.ItemImage : VSImageLibrary.ExecutableStopped; }
51    }
52    #endregion
53
54    [Storable]
55    private TerminationCriterium terminationCriterium;
56    public TerminationCriterium TerminationCriterium {
57      get { return terminationCriterium; }
58      set {
59        if (terminationCriterium == value) return;
60        terminationCriterium = value;
61        OnPropertyChanged("TerminationCriterium");
62      }
63    }
64
65    [Storable]
66    private TimeSpan maximumExecutionTime;
67    public TimeSpan MaximumExecutionTime {
68      get { return maximumExecutionTime; }
69      set {
70        if (maximumExecutionTime == value) return;
71        maximumExecutionTime = value;
72        OnPropertyChanged("MaximumExecutionTime");
73      }
74    }
75
76    [Storable]
77    private int maximumEvaluations;
78    public int MaximumEvaluations {
79      get { return maximumEvaluations; }
80      set {
81        if (maximumEvaluations == value) return;
82        maximumEvaluations = value;
83        OnPropertyChanged("MaximumEvaluations");
84      }
85    }
86
87    [Storable]
88    private double targetValue;
89    public double TargetValue {
90      get { return targetValue; }
91      set {
92        if (targetValue == value) return;
93        targetValue = value;
94        OnPropertyChanged("TargetValue");
95      }
96    }
97
98    [Storable]
99    private bool maximization;
100    public bool Maximization {
101      get { return maximization; }
102      private set {
103        if (maximization == value) return;
104        maximization = value;
105        OnPropertyChanged("Maximization");
106      }
107    }
108
109    [Storable]
110    private double moveCostPerSolution;
111    public double MoveCostPerSolution {
112      get { return moveCostPerSolution; }
113      set {
114        if (moveCostPerSolution == value) return;
115        moveCostPerSolution = value;
116        OnPropertyChanged("MoveCostPerSolution");
117      }
118    }
119
120
121    public ExecutionState ExecutionState {
122      get { return (Algorithm != null) ? Algorithm.ExecutionState : ExecutionState.Stopped; }
123    }
124
125    private TimeSpan lastAlgorithmExecutionTime;
126    [Storable]
127    private TimeSpan executionTime;
128    public TimeSpan ExecutionTime {
129      get { return executionTime; }
130      set {
131        if (executionTime == value) return;
132        executionTime = value;
133        OnPropertyChanged("ExecutionTime");
134        OnExecutionTimeChanged();
135      }
136    }
137
138    private int lastAlgorithmEvaluatedSolutions;
139    private int lastAlgorithmEvaluatedMoves;
140    [Storable]
141    private double evaluations;
142    public double Evaluations {
143      get { return evaluations; }
144      set {
145        if (evaluations == value) return;
146        evaluations = value;
147        OnPropertyChanged("Evaluations");
148      }
149    }
150
151    [Storable]
152    private double bestSoFar;
153    public double BestSoFar {
154      get { return bestSoFar; }
155      set {
156        if (bestSoFar == value) return;
157        bestSoFar = value;
158        OnPropertyChanged("BestSoFar");
159      }
160    }
161
162    [Storable]
163    private IRun currentRun;
164    public IRun CurrentRun {
165      get { return currentRun; }
166      private set {
167        if (currentRun == value) return;
168        currentRun = value;
169        OnPropertyChanged("CurrentRun");
170      }
171    }
172
173    [Storable]
174    private IAlgorithm algorithm;
175    public IAlgorithm Algorithm {
176      get { return algorithm; }
177      set {
178        if (algorithm == value) return;
179        if (algorithm != null) DeregisterAlgorithmEvents();
180        algorithm = value;
181        if (algorithm != null) {
182          RegisterAlgorithmEvents();
183        }
184        OnPropertyChanged("Algorithm");
185        Prepare();
186      }
187    }
188
189    [Storable]
190    private RunCollection runs;
191    public RunCollection Runs {
192      get { return runs; }
193      private set {
194        if (value == null) throw new ArgumentNullException();
195        if (runs == value) return;
196        runs = value;
197        OnPropertyChanged("Runs");
198      }
199    }
200
201    public IEnumerable<IOptimizer> NestedOptimizers {
202      get {
203        if (Algorithm == null) yield break;
204        yield return Algorithm;
205        foreach (var opt in Algorithm.NestedOptimizers)
206          yield return opt;
207      }
208    }
209
210    private bool IsFinished {
211      get {
212        var timeHit = ExecutionTime >= MaximumExecutionTime;
213        var evalHit = Evaluations >= MaximumEvaluations;
214        var targetHit = (Maximization && BestSoFar >= TargetValue || !Maximization && BestSoFar <= TargetValue);
215
216        return timeHit && evalHit && targetHit
217          || timeHit && (TerminationCriterium == TerminationCriterium.OnlyByTime
218                      || TerminationCriterium == TerminationCriterium.ByTargetAndTime
219                      || TerminationCriterium == TerminationCriterium.WhicheverHitsFirst)
220          || evalHit && (TerminationCriterium == TerminationCriterium.OnlyByEvaluations
221                      || TerminationCriterium == TerminationCriterium.ByTargetAndEvaluations
222                      || TerminationCriterium == TerminationCriterium.WhicheverHitsFirst)
223          || targetHit && (TerminationCriterium == TerminationCriterium.OnlyByTarget
224                        || TerminationCriterium == TerminationCriterium.WhicheverHitsFirst
225                        || TerminationCriterium == TerminationCriterium.ByTargetAndTime
226                        || TerminationCriterium == TerminationCriterium.ByTargetAndEvaluations);
227      }
228    }
229
230    [StorableConstructor]
231    private IndepdentRandomRestartRun(bool deserializing) : base(deserializing) { }
232    private IndepdentRandomRestartRun(IndepdentRandomRestartRun original, Cloner cloner)
233      : base(original, cloner) {
234      terminationCriterium = original.terminationCriterium;
235      maximumExecutionTime = original.maximumExecutionTime;
236      maximumEvaluations = original.maximumEvaluations;
237      targetValue = original.targetValue;
238      executionTime = original.executionTime;
239      evaluations = original.evaluations;
240      bestSoFar = original.bestSoFar;
241      lastAlgorithmExecutionTime = original.lastAlgorithmExecutionTime;
242      lastAlgorithmEvaluatedSolutions = original.lastAlgorithmEvaluatedSolutions;
243      lastAlgorithmEvaluatedMoves = original.lastAlgorithmEvaluatedMoves;
244
245      algorithm = cloner.Clone(original.algorithm);
246      runs = cloner.Clone(original.runs);
247
248      Initialize();
249    }
250    public IndepdentRandomRestartRun()
251      : base() {
252      name = ItemName;
253      description = ItemDescription;
254      terminationCriterium = TerminationCriterium.OnlyByEvaluations;
255      maximumExecutionTime = TimeSpan.FromMinutes(1);
256      maximumEvaluations = 10000000; // 10 mio
257      targetValue = 0;
258      executionTime = TimeSpan.Zero;
259      evaluations = 0;
260      bestSoFar = double.NaN;
261      lastAlgorithmExecutionTime = TimeSpan.Zero;
262      lastAlgorithmEvaluatedSolutions = 0;
263      lastAlgorithmEvaluatedMoves = 0;
264
265      Runs = new RunCollection { OptimizerName = Name };
266      Initialize();
267    }
268    public IndepdentRandomRestartRun(string name)
269      : base(name) {
270      description = ItemDescription;
271      terminationCriterium = TerminationCriterium.OnlyByEvaluations;
272      maximumExecutionTime = TimeSpan.FromMinutes(1);
273      maximumEvaluations = 10000000; // 10 mio
274      targetValue = 0;
275      executionTime = TimeSpan.Zero;
276      evaluations = 0;
277      bestSoFar = double.NaN;
278      lastAlgorithmExecutionTime = TimeSpan.Zero;
279      lastAlgorithmEvaluatedSolutions = 0;
280      lastAlgorithmEvaluatedMoves = 0;
281
282      Runs = new RunCollection { OptimizerName = Name };
283      Initialize();
284    }
285    public IndepdentRandomRestartRun(string name, string description)
286      : base(name, description) {
287      terminationCriterium = TerminationCriterium.OnlyByEvaluations;
288      maximumExecutionTime = TimeSpan.FromMinutes(1);
289      maximumEvaluations = 10000000; // 10 mio
290      targetValue = 0;
291      executionTime = TimeSpan.Zero;
292      evaluations = 0;
293      bestSoFar = double.NaN;
294      lastAlgorithmExecutionTime = TimeSpan.Zero;
295      lastAlgorithmEvaluatedSolutions = 0;
296      lastAlgorithmEvaluatedMoves = 0;
297
298      Runs = new RunCollection { OptimizerName = Name };
299      Initialize();
300    }
301
302    public override IDeepCloneable Clone(Cloner cloner) {
303      if (ExecutionState == ExecutionState.Started) throw new InvalidOperationException(string.Format("Clone not allowed in execution state \"{0}\".", ExecutionState));
304      return new IndepdentRandomRestartRun(this, cloner);
305    }
306
307    [StorableHook(HookType.AfterDeserialization)]
308    private void AfterDeserialization() {
309      Initialize();
310    }
311
312    private void Initialize() {
313      if (algorithm != null) RegisterAlgorithmEvents();
314    }
315
316    public void Prepare() {
317      Prepare(false);
318    }
319    public void Prepare(bool clearRuns) {
320      executionTime = TimeSpan.Zero;
321      evaluations = 0;
322      lastAlgorithmExecutionTime = TimeSpan.Zero;
323      lastAlgorithmEvaluatedSolutions = 0;
324
325      Algorithm.Prepare(clearRuns);
326    }
327    public void Start() {
328      if (ExecutionState == ExecutionState.Prepared) {
329        currentRun = new Run(Algorithm) {
330          Name = Algorithm.Name + " IRRRun" + Runs.Count
331        };
332      }
333      Algorithm.Start();
334    }
335    public void Pause() {
336      Algorithm.Pause();
337    }
338    public void Stop() {
339      Algorithm.Stop();
340    }
341
342    #region Events
343    protected override void OnNameChanged() {
344      base.OnNameChanged();
345      runs.OptimizerName = Name;
346    }
347
348    public event PropertyChangedEventHandler PropertyChanged;
349    private void OnPropertyChanged(string property) {
350      var handler = PropertyChanged;
351      if (handler != null) handler(this, new PropertyChangedEventArgs(property));
352    }
353
354    #region IExecutable Events
355    public event EventHandler ExecutionStateChanged;
356    private void OnExecutionStateChanged() {
357      var handler = ExecutionStateChanged;
358      if (handler != null) handler(this, EventArgs.Empty);
359    }
360    public event EventHandler ExecutionTimeChanged;
361    private void OnExecutionTimeChanged() {
362      var handler = ExecutionTimeChanged;
363      if (handler != null) handler(this, EventArgs.Empty);
364    }
365    public event EventHandler Prepared;
366    private void OnPrepared() {
367      var handler = Prepared;
368      if (handler != null) handler(this, EventArgs.Empty);
369    }
370    public event EventHandler Started;
371    private void OnStarted() {
372      var handler = Started;
373      if (handler != null) handler(this, EventArgs.Empty);
374    }
375    public event EventHandler Paused;
376    private void OnPaused() {
377      var handler = Paused;
378      if (handler != null) handler(this, EventArgs.Empty);
379    }
380    public event EventHandler Stopped;
381    private void OnStopped() {
382      var handler = Stopped;
383      if (handler != null) handler(this, EventArgs.Empty);
384    }
385    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
386    private void OnExceptionOccurred(Exception exception) {
387      var handler = ExceptionOccurred;
388      if (handler != null) handler(this, new EventArgs<Exception>(exception));
389    }
390    #endregion
391
392    #region Algorithm Events
393    private void RegisterAlgorithmEvents() {
394      algorithm.ExceptionOccurred += Algorithm_ExceptionOccurred;
395      algorithm.ExecutionTimeChanged += Algorithm_ExecutionTimeChanged;
396      algorithm.ExecutionStateChanged += Algorithm_ExecutionStateChanged;
397      algorithm.Paused += Algorithm_Paused;
398      algorithm.Prepared += Algorithm_Prepared;
399      algorithm.Started += Algorithm_Started;
400      algorithm.Stopped += Algorithm_Stopped;
401      algorithm.ProblemChanged += Algorithm_ProblemChanged;
402    }
403    private void DeregisterAlgorithmEvents() {
404      algorithm.ExceptionOccurred -= Algorithm_ExceptionOccurred;
405      algorithm.ExecutionTimeChanged -= Algorithm_ExecutionTimeChanged;
406      algorithm.ExecutionStateChanged -= Algorithm_ExecutionStateChanged;
407      algorithm.Paused -= Algorithm_Paused;
408      algorithm.Prepared -= Algorithm_Prepared;
409      algorithm.Started -= Algorithm_Started;
410      algorithm.Stopped -= Algorithm_Stopped;
411      algorithm.ProblemChanged -= Algorithm_ProblemChanged;
412    }
413    private void Algorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
414      OnExceptionOccurred(e.Value);
415    }
416    private void Algorithm_ExecutionTimeChanged(object sender, EventArgs e) {
417      ExecutionTime += Algorithm.ExecutionTime - lastAlgorithmExecutionTime;
418      lastAlgorithmExecutionTime = Algorithm.ExecutionTime;
419
420      UpdateAlgorithmResults();
421
422      if (IsFinished) {
423        Algorithm.Stop();
424      }
425      OnExecutionTimeChanged();
426    }
427
428    private void Algorithm_ExecutionStateChanged(object sender, EventArgs e) {
429      OnExecutionStateChanged();
430    }
431    private void Algorithm_Paused(object sender, EventArgs e) {
432      ExecutionTime += Algorithm.ExecutionTime - lastAlgorithmExecutionTime;
433      lastAlgorithmExecutionTime = Algorithm.ExecutionTime;
434
435      UpdateAlgorithmResults();
436      OnPaused();
437    }
438    private void Algorithm_Prepared(object sender, EventArgs e) {
439      OnPrepared();
440    }
441    private void Algorithm_Started(object sender, EventArgs e) {
442      OnStarted();
443    }
444    private void Algorithm_Stopped(object sender, EventArgs e) {
445      ExecutionTime += Algorithm.ExecutionTime - lastAlgorithmExecutionTime;
446      lastAlgorithmExecutionTime = Algorithm.ExecutionTime;
447
448      var bestQuality = UpdateAlgorithmResults();
449
450      foreach (var result in Algorithm.Results) {
451        if (result.Name == "QualityPerClock") {
452          if (!currentRun.Results.ContainsKey(result.Name))
453            currentRun.Results.Add(result.Name, (IItem)result.Value.Clone());
454          else {
455            var dt = (IndexedDataTable<double>)currentRun.Results[result.Name];
456            var execTime = ((TimeSpanValue)currentRun.Results["ExecutionTime"]).Value.TotalSeconds;
457            var best = dt.Rows.First().Values.Last().Item2;
458            var resultDt = (IndexedDataTable<double>)result.Value;
459            foreach (var tupl in resultDt.Rows.First().Values) {
460              if (Maximization && tupl.Item2 > best || !Maximization && tupl.Item2 < best) {
461                dt.Rows.First().Values.Add(Tuple.Create(execTime + tupl.Item1, tupl.Item2));
462                best = tupl.Item2;
463              }
464            }
465          }
466        } else if (result.Name == "QualityPerEvaluations") {
467          if (!currentRun.Results.ContainsKey(result.Name))
468            currentRun.Results.Add(result.Name, (IItem)result.Value.Clone());
469          else {
470            var dt = (IndexedDataTable<double>)currentRun.Results[result.Name];
471            var evalSols = ((DoubleValue)currentRun.Results["EvaluatedSolutions"]).Value;
472            var evalMoves = ((DoubleValue)currentRun.Results["EvaluatedMoves"]).Value;
473            var best = dt.Rows.First().Values.Last().Item2;
474            var resultDt = (IndexedDataTable<double>)result.Value;
475            foreach (var tupl in resultDt.Rows.First().Values) {
476              if (Maximization && tupl.Item2 > best || !Maximization && tupl.Item2 < best) {
477                dt.Rows.First().Values.Add(Tuple.Create(evalSols + moveCostPerSolution * evalMoves + tupl.Item1, tupl.Item2));
478                best = tupl.Item2;
479              }
480            }
481          }
482        } else if (result.Name == "EvaluatedSolutions") {
483          currentRun.Results.Add(result.Name, (IItem)result.Value.Clone());
484        } else if (result.Name == "EvaluatedMoves") {
485          currentRun.Results.Add(result.Name, (IItem)result.Value.Clone());
486        } else if (result.Name == "ExecutionTime") {
487          currentRun.Results.Add(result.Name, (IItem)result.Value.Clone());
488        } else if (result.Name == "BestQuality") {
489          currentRun.Results.Add(result.Name, (IItem)result.Value.Clone());
490        } else if (result.Name.ToLower().EndsWith("solution") && BestSoFar == bestQuality) {
491          currentRun.Results.Add(result.Name, (IItem)result.Value.Clone());
492        }
493      }
494      foreach (var result in Algorithm.Results) {
495        if (result.Name == "QualityPerClock") {
496
497        } else if (result.Name == "QualityPerEvaluations") {
498        } else if (result.Name == "EvaluatedSolutions") {
499          currentRun.Results.Add(result.Name, (IItem)result.Value.Clone());
500        } else if (result.Name == "EvaluatedMoves") {
501          currentRun.Results.Add(result.Name, (IItem)result.Value.Clone());
502        } else if (result.Name == "ExecutionTime") {
503          currentRun.Results.Add(result.Name, (IItem)result.Value.Clone());
504        } else if (result.Name == "BestQuality") {
505          currentRun.Results.Add(result.Name, (IItem)result.Value.Clone());
506        } else if (result.Name.ToLower().EndsWith("solution") && BestSoFar == bestQuality) {
507          currentRun.Results.Add(result.Name, (IItem)result.Value.Clone());
508        }
509      }
510
511
512      if (IsFinished) {
513
514      }
515
516      // TODO
517      var cloner = new Cloner();
518      var algRun = cloner.Clone(Algorithm.Runs.Last());
519      Runs.Add(algRun);
520      Algorithm.Runs.Clear();
521      OnStopped();
522    }
523
524    private double UpdateAlgorithmResults() {
525      IResult evaluationsResult;
526      if (Algorithm.Results.TryGetValue("EvaluatedSolutions", out evaluationsResult)) {
527        var evals = ((IntValue)evaluationsResult.Value).Value;
528        Evaluations += evals - lastAlgorithmEvaluatedSolutions;
529        lastAlgorithmEvaluatedSolutions = evals;
530      }
531      if (Algorithm.Results.TryGetValue("EvaluatedMoves", out evaluationsResult)) {
532        var evals = ((IntValue)evaluationsResult.Value).Value;
533        Evaluations += moveCostPerSolution * (evals - lastAlgorithmEvaluatedMoves);
534        lastAlgorithmEvaluatedMoves = evals;
535      }
536      if (Algorithm.Results.TryGetValue("BestQuality", out evaluationsResult)) {
537        var bestQuality = ((DoubleValue)evaluationsResult).Value;
538        if (double.IsNaN(BestSoFar)
539            || Maximization && bestQuality > BestSoFar
540            || !Maximization && bestQuality < BestSoFar)
541          BestSoFar = bestQuality;
542        return bestQuality;
543      }
544      return double.NaN;
545    }
546
547    private void Algorithm_ProblemChanged(object sender, EventArgs e) {
548      var soProblem = Algorithm.Problem as ISingleObjectiveHeuristicOptimizationProblem;
549      if (soProblem == null) return;
550      var maxParam = soProblem.MaximizationParameter as IValueParameter<BoolValue>;
551      if (maxParam != null)
552        Maximization = maxParam.Value.Value;
553      var bkParam = soProblem.BestKnownQualityParameter as IValueParameter<DoubleValue>;
554      if (bkParam != null && bkParam.Value != null)
555        TargetValue = bkParam.Value.Value;
556    }
557    #endregion
558    #endregion
559  }
560}
Note: See TracBrowser for help on using the repository browser.