Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/Evaluators/ParameterConfigurationEvaluator.cs @ 5184

Last change on this file since 5184 was 5184, checked in by cneumuel, 13 years ago

#1215

  • enhanced combinations generator (now with batchruns!)
  • fixed ActualNames for metaopt-alg
  • added penalty for invalid solution-candidates (algs which throw exceptions)
  • migrated to .NET 4.0
File size: 7.5 KB
Line 
1using System;
2using System.Linq;
3using System.Threading;
4using HeuristicLab.Common;
5using HeuristicLab.Core;
6using HeuristicLab.Data;
7using HeuristicLab.Operators;
8using HeuristicLab.Optimization;
9using HeuristicLab.Parameters;
10using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
11using System.Collections.Generic;
12
13namespace HeuristicLab.Problems.MetaOptimization {
14  /// <summary>
15  /// A base class for operators which evaluate TSP solutions.
16  /// </summary>
17  [Item("ParameterConfigurationEvaluator", "A base class for operators which evaluate Meta Optimization solutions.")]
18  [StorableClass]
19  public class ParameterConfigurationEvaluator : SingleSuccessorOperator, IParameterConfigurationEvaluator {
20    private bool algorithmStopped;
21    private bool algorithmExceptionOccured;
22
23    public ILookupParameter<DoubleValue> QualityParameter {
24      get { return (ILookupParameter<DoubleValue>)Parameters["Quality"]; }
25    }
26    public ILookupParameter<EngineAlgorithm> AlgorithmParameter {
27      get { return (ILookupParameter<EngineAlgorithm>)Parameters[MetaOptimizationProblem.AlgorithmTypeParameterName]; }
28    }
29    public ILookupParameter<IItemList<ISingleObjectiveProblem>> ProblemsParameter {
30      get { return (ILookupParameter<IItemList<ISingleObjectiveProblem>>)Parameters[MetaOptimizationProblem.ProblemsParameterName]; }
31    }
32    public ILookupParameter<ParameterConfigurationTree> ParameterConfigurationParameter {
33      get { return (ILookupParameter<ParameterConfigurationTree>)Parameters["ParameterConfigurationTree"]; }
34    }
35    public LookupParameter<IntValue> RepetitionsParameter {
36      get { return (LookupParameter<IntValue>)Parameters[MetaOptimizationProblem.RepetitionsParameterName]; }
37    }
38
39    public IntValue Repetitions {
40      get { return RepetitionsParameter.ActualValue; }
41    }
42
43    public ParameterConfigurationEvaluator()
44      : base() {
45      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The evaluated quality of the ParameterVector."));
46      Parameters.Add(new LookupParameter<EngineAlgorithm>(MetaOptimizationProblem.AlgorithmTypeParameterName, "Missing description."));
47      Parameters.Add(new LookupParameter<IItemList<ISingleObjectiveProblem>>(MetaOptimizationProblem.ProblemsParameterName, "Missing description."));
48      Parameters.Add(new LookupParameter<ParameterConfigurationTree>("ParameterConfigurationTree", "Missing description."));
49      Parameters.Add(new LookupParameter<IntValue>(MetaOptimizationProblem.RepetitionsParameterName, "Number of evaluations on one problem."));
50    }
51
52    [StorableConstructor]
53    protected ParameterConfigurationEvaluator(bool deserializing) : base(deserializing) { }
54    protected ParameterConfigurationEvaluator(ParameterConfigurationEvaluator original, Cloner cloner)
55      : base(original, cloner) {
56      this.algorithmStopped = original.algorithmStopped;
57    }
58    public override IDeepCloneable Clone(Cloner cloner) {
59      return new ParameterConfigurationEvaluator(this, cloner);
60    }
61
62    public override IOperation Apply() {
63      EngineAlgorithm algorithm = AlgorithmParameter.ActualValue;
64      IItemList<ISingleObjectiveProblem> problems = ProblemsParameter.ActualValue;
65
66      // set parameters
67      ParameterConfigurationParameter.ActualValue.Parameterize(algorithm);
68      algorithm.Problem = problems.First();
69      algorithm.StoreAlgorithmInEachRun = false;
70
71      algorithmStopped = false;
72      algorithmExceptionOccured = false;
73      algorithm.Stopped += new EventHandler(algorithm_Stopped);
74      algorithm.Paused += new EventHandler(algorithm_Paused);
75      algorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(algorithm_ExceptionOccurred);
76
77      List<double> qualities = new List<double>();
78      List<TimeSpan> executionTimes = new List<TimeSpan>();
79      algorithm.Engine = new SequentialEngine.SequentialEngine();
80      algorithm.Prepare(true);
81
82      foreach (ISingleObjectiveProblem problem in problems) {
83        algorithm.Problem = problem;
84
85        for (int i = 0; i < Repetitions.Value; i++) {
86          algorithm.Prepare();
87          algorithm.Start();
88          while (!algorithmStopped) {
89            Thread.Sleep(200); // wait for algorithm to complete; do not rely on Algorithm.ExecutionState here, because change of ExecutionState happens before Run is added (which causes problems because Algorithm might get cloned when its started already)
90          }
91
92          if (algorithmExceptionOccured) {
93            // this parametercombination was bad. set penalty for this solution
94            qualities.Add(double.MaxValue); // todo: respect Maximization
95            executionTimes.Add(algorithm.ExecutionTime);
96          } else {
97            qualities.Add(((DoubleValue)algorithm.Results["BestQuality"].Value).Value);
98            executionTimes.Add(algorithm.ExecutionTime);
99
100            // parameters will be stored in ParameterConfigurationTree anyway. they would be redundant in runs
101            algorithm.Runs.Last().Parameters.Clear();
102            // but keep the problem, since this differs in runs
103            algorithm.Runs.Last().Parameters.Add("Problem", problem);
104          }
105          algorithmStopped = false;
106          algorithmExceptionOccured = false;
107        }
108      }
109
110      algorithm.Stopped -= new EventHandler(algorithm_Stopped);
111      algorithm.Paused -= new EventHandler(algorithm_Paused);
112      algorithm.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(algorithm_ExceptionOccurred);
113      algorithm.Prepare();
114
115      qualities = qualities.OrderBy(x => x).ToList();  // todo: respect Maximization:true/false
116
117      ParameterConfigurationParameter.ActualValue.AverageExecutionTime = new TimeSpanValue(TimeSpan.FromMilliseconds(executionTimes.Average(t => t.TotalMilliseconds)));
118      ParameterConfigurationParameter.ActualValue.Repetitions = (IntValue)Repetitions.Clone();
119      ParameterConfigurationParameter.ActualValue.BestQuality = new DoubleValue(qualities.First());
120      ParameterConfigurationParameter.ActualValue.AverageQuality = new DoubleValue(qualities.Average());
121      ParameterConfigurationParameter.ActualValue.WorstQuality = new DoubleValue(qualities.Last());
122      ParameterConfigurationParameter.ActualValue.QualityVariance = new DoubleValue(qualities.Variance());
123      ParameterConfigurationParameter.ActualValue.QualityStandardDeviation = new DoubleValue(qualities.StandardDeviation());
124      ParameterConfigurationParameter.ActualValue.Runs = (RunCollection)algorithm.Runs.Clone();
125
126      double quality = ParameterConfigurationParameter.ActualValue.AverageQuality.Value; // todo: also include other measures (executiontime, variance)
127      this.QualityParameter.ActualValue = new DoubleValue(quality);
128
129      return base.Apply();
130    }
131
132    private void algorithm_Paused(object sender, EventArgs e) {
133      algorithmStopped = true;
134    }
135
136    private void algorithm_Stopped(object sender, EventArgs e) {
137      algorithmStopped = true;
138    }
139
140    void algorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
141      algorithmExceptionOccured = true;
142    }
143
144    public static double Variance(IEnumerable<double> source) {
145      double avg = source.Average();
146      double d = source.Aggregate(0.0, (total, next) => total += Math.Pow(next - avg, 2));
147      return d / (source.Count() - 1);
148    }
149
150    public static double StandardDeviation(IEnumerable<double> source) {
151      return Math.Sqrt(source.Variance());
152    }
153
154
155  }
156}
Note: See TracBrowser for help on using the repository browser.