Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.MetaOptimization (trunk integration)/HeuristicLab.Problems.MetaOptimization/3.3/MetaOptimizationProblem.cs @ 12547

Last change on this file since 12547 was 8576, checked in by jkarder, 12 years ago

#1853: created branch for MetaOptimization (trunk integration)

File size: 19.3 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.Linq;
24using HeuristicLab.Algorithms.GeneticAlgorithm;
25using HeuristicLab.Collections;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.ParameterConfigurationEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Problems.DataAnalysis;
35using HeuristicLab.Problems.TestFunctions;
36
37namespace HeuristicLab.Problems.MetaOptimization {
38  /// <summary>
39  ///
40  /// </summary>
41  [Item("Meta Optimization Problem", "Represents a meta-optimization problem.")]
42  [Creatable("Problems")]
43  [StorableClass]
44  public sealed class MetaOptimizationProblem : SingleObjectiveHeuristicOptimizationProblem<IParameterConfigurationEvaluator, IParameterConfigurationCreator>, IStorableContent {
45    public string Filename { get; set; }
46
47    public const string AlgorithmTypeParameterName = "AlgorithmType";
48    public const string ProblemTypeParameterName = "ProblemType";
49    public const string ProblemsParameterName = "Problems";
50    public const string ParameterConfigurationTreeParameterName = "ParameterConfiguration";
51    public const string RepetitionsParameterName = "Repetitions";
52    public const string QualityMeasureNameName = "QualityMeasureName";
53
54    public const string IntValueManipulatorParameterName = "IntValueManipulator";
55    public const string DoubleValueManipulatorParameterName = "DoubleValueManipulator";
56    public const string IntValueCrossoverParameterName = "IntValueCrossover";
57    public const string DoubleValueCrossoverParameterName = "DoubleValueCrossover";
58    public const string QualityWeightParameterName = "QualityWeight";
59    public const string StandardDeviationWeightParameterName = "StandardDeviationWeight";
60    public const string EvaluatedSolutionsWeightParameterName = "EvaluatedSolutionsWeight";
61
62
63    #region Parameter Properties
64    public IValueParameter<ConstrainedTypeValue<IAlgorithm>> AlgorithmTypeParameter {
65      get { return (ValueParameter<ConstrainedTypeValue<IAlgorithm>>)Parameters[AlgorithmTypeParameterName]; }
66    }
67    public IValueParameter<ConstrainedTypeValue<IProblem>> ProblemTypeParameter {
68      get { return (ValueParameter<ConstrainedTypeValue<IProblem>>)Parameters[ProblemTypeParameterName]; }
69    }
70    public IValueParameter<ConstrainedItemList<IProblem>> ProblemsParameter {
71      get { return (ValueParameter<ConstrainedItemList<IProblem>>)Parameters[ProblemsParameterName]; }
72    }
73    public IValueParameter<ParameterConfigurationTree> ParameterConfigurationTreeParameter {
74      get { return (OptionalValueParameter<ParameterConfigurationTree>)Parameters[ParameterConfigurationTreeParameterName]; }
75    }
76    public IValueParameter<IntValue> RepetitionsParameter {
77      get { return (ValueParameter<IntValue>)Parameters[RepetitionsParameterName]; }
78    }
79    public IConstrainedValueParameter<IIntValueManipulator> IntValueManipulatorParameter {
80      get { return (ConstrainedValueParameter<IIntValueManipulator>)Parameters[IntValueManipulatorParameterName]; }
81    }
82    public IConstrainedValueParameter<IDoubleValueManipulator> DoubleValueManipulatorParameter {
83      get { return (ConstrainedValueParameter<IDoubleValueManipulator>)Parameters[DoubleValueManipulatorParameterName]; }
84    }
85    public IValueParameter<StringValue> QualityMeasureNameParameter {
86      get { return (ValueParameter<StringValue>)Parameters[QualityMeasureNameName]; }
87    }
88    public IConstrainedValueParameter<IIntValueCrossover> IntValueCrossoverParameter {
89      get { return (ConstrainedValueParameter<IIntValueCrossover>)Parameters[IntValueCrossoverParameterName]; }
90    }
91    public IConstrainedValueParameter<IDoubleValueCrossover> DoubleValueCrossoverParameter {
92      get { return (ConstrainedValueParameter<IDoubleValueCrossover>)Parameters[DoubleValueCrossoverParameterName]; }
93    }
94    #endregion
95
96    #region Properties
97    public IAlgorithm Algorithm {
98      get { return CreateAlgorithm(AlgorithmType.Value, Problems.FirstOrDefault()); }
99    }
100    public ConstrainedTypeValue<IAlgorithm> AlgorithmType {
101      get { return AlgorithmTypeParameter.Value; }
102      set { AlgorithmTypeParameter.Value = value; }
103    }
104    public ConstrainedTypeValue<IProblem> ProblemType {
105      get { return ProblemTypeParameter.Value; }
106      set { ProblemTypeParameter.Value = value; }
107    }
108    public ConstrainedItemList<IProblem> Problems {
109      get { return ProblemsParameter.Value; }
110      set { ProblemsParameter.Value = value; }
111    }
112    public ParameterConfigurationTree ParameterConfigurationTree {
113      get { return ParameterConfigurationTreeParameter.Value; }
114      set { ParameterConfigurationTreeParameter.Value = value; }
115    }
116    public IntValue Repetitions {
117      get { return RepetitionsParameter.Value; }
118      set { RepetitionsParameter.Value = value; }
119    }
120    private BestParameterConfigurationAnalyzer BestParameterConfigurationAnalyzer {
121      get { return Operators.OfType<BestParameterConfigurationAnalyzer>().FirstOrDefault(); }
122    }
123    private ReferenceQualityAnalyzer ReferenceQualityAnalyzer {
124      get { return Operators.OfType<ReferenceQualityAnalyzer>().FirstOrDefault(); }
125    }
126    private SolutionCacheAnalyzer RunsAnalyzer {
127      get { return Operators.OfType<SolutionCacheAnalyzer>().FirstOrDefault(); }
128    }
129    private PMOPopulationDiversityAnalyzer PMOPopulationDiversityAnalyzer {
130      get { return Operators.OfType<PMOPopulationDiversityAnalyzer>().FirstOrDefault(); }
131    }
132    private PMOProblemQualitiesAnalyzer PMOProblemQualitiesAnalyzer {
133      get { return Operators.OfType<PMOProblemQualitiesAnalyzer>().FirstOrDefault(); }
134    }
135    private PMOBestSolutionHistoryAnalyzer PMOBestSolutionHistoryAnalyzer {
136      get { return Operators.OfType<PMOBestSolutionHistoryAnalyzer>().FirstOrDefault(); }
137    }
138    #endregion
139
140    #region Constructors and Cloning
141    public MetaOptimizationProblem()
142      : base() {
143      Parameters.Add(new ValueParameter<ConstrainedTypeValue<IAlgorithm>>(AlgorithmTypeParameterName, "The algorithm which's parameters should be optimized.", new ConstrainedTypeValue<IAlgorithm>(typeof(GeneticAlgorithm))));
144      Parameters.Add(new ValueParameter<ConstrainedTypeValue<IProblem>>(ProblemTypeParameterName, "The problem type.", new ConstrainedTypeValue<IProblem>()));
145      Parameters.Add(new ValueParameter<ConstrainedItemList<IProblem>>(ProblemsParameterName, "The problems that should be evaluated.", new ConstrainedItemList<IProblem>()));
146      Parameters.Add(new OptionalValueParameter<ParameterConfigurationTree>(ParameterConfigurationTreeParameterName, "Tree of algorithm parameters that should be optimized.")); // needs to be optional, when last problem is removed from list, it must be set null
147      Parameters.Add(new ValueParameter<IntValue>(RepetitionsParameterName, "The number of evaluations for each problem.", new IntValue(3)));
148      Parameters.Add(new ValueParameter<StringValue>(QualityMeasureNameName, "The name of the quality result of the base-level algorithm. Subresults can be accessed by dot separator.", new StringValue("BestQuality")));
149
150      var validIntManipulators = new ItemSet<IIntValueManipulator>(ApplicationManager.Manager.GetInstances<IIntValueManipulator>());
151      var validDoubleManipulators = new ItemSet<IDoubleValueManipulator>(ApplicationManager.Manager.GetInstances<IDoubleValueManipulator>());
152      var validIntCrossovers = new ItemSet<IIntValueCrossover>(ApplicationManager.Manager.GetInstances<IIntValueCrossover>());
153      var validDoubleCrossovers = new ItemSet<IDoubleValueCrossover>(ApplicationManager.Manager.GetInstances<IDoubleValueCrossover>());
154      Parameters.Add(new ConstrainedValueParameter<IIntValueManipulator>(IntValueManipulatorParameterName, validIntManipulators, validIntManipulators.Where(x => x.GetType() == typeof(NormalIntValueManipulator)).SingleOrDefault()));
155      Parameters.Add(new ConstrainedValueParameter<IDoubleValueManipulator>(DoubleValueManipulatorParameterName, validDoubleManipulators, validDoubleManipulators.Where(x => x.GetType() == typeof(NormalDoubleValueManipulator)).SingleOrDefault()));
156      Parameters.Add(new ConstrainedValueParameter<IIntValueCrossover>(IntValueCrossoverParameterName, validIntCrossovers, validIntCrossovers.Where(x => x.GetType() == typeof(NormalIntValueCrossover)).SingleOrDefault()));
157      Parameters.Add(new ConstrainedValueParameter<IDoubleValueCrossover>(DoubleValueCrossoverParameterName, validDoubleCrossovers, validDoubleCrossovers.Where(x => x.GetType() == typeof(NormalDoubleValueCrossover)).SingleOrDefault()));
158
159      Parameters.Add(new ValueParameter<DoubleValue>(QualityWeightParameterName, new DoubleValue(1)));
160      Parameters.Add(new ValueParameter<DoubleValue>(StandardDeviationWeightParameterName, new DoubleValue(0.01)));
161      Parameters.Add(new ValueParameter<DoubleValue>(EvaluatedSolutionsWeightParameterName, new DoubleValue(0.0005)));
162
163      Maximization = new BoolValue(false);
164      SolutionCreator = new RandomParameterConfigurationCreator();
165      Evaluator = new PMOEvaluator();
166
167      InitializeOperators();
168      RegisterParameterEvents();
169      ParameterizeAnalyzer();
170      ParameterizeSolutionCreator();
171      ParameterizeEvaluator();
172      ParameterizeOperators();
173
174      AlgorithmTypeParameter_ValueChanged(this, EventArgs.Empty);
175    }
176
177    [StorableConstructor]
178    private MetaOptimizationProblem(bool deserializing) : base(deserializing) { }
179    private MetaOptimizationProblem(MetaOptimizationProblem original, Cloner cloner)
180      : base(original, cloner) {
181      this.RegisterParameterEvents();
182    }
183    public override IDeepCloneable Clone(Cloner cloner) {
184      return new MetaOptimizationProblem(this, cloner);
185    }
186    #endregion
187
188    #region Helpers
189    [StorableHook(HookType.AfterDeserialization)]
190    private void AfterDeserializationHook() {
191      if (!Parameters.ContainsKey(QualityMeasureNameName)) Parameters.Add(new ValueParameter<StringValue>(QualityMeasureNameName, "The name of the quality result of the base-level algorithm. Subresults can be accessed by dot separator.", new StringValue("BestQuality"))); // backwards compatibility
192      RegisterParameterEvents();
193    }
194    private void RegisterParameterEvents() {
195      SolutionCreatorParameter.ValueChanged += new EventHandler(SolutionCreatorParameter_ValueChanged);
196      EvaluatorParameter.ValueChanged += new EventHandler(EvaluatorParameter_ValueChanged);
197      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
198      AlgorithmTypeParameter.ValueChanged += new EventHandler(AlgorithmTypeParameter_ValueChanged);
199      AlgorithmType.ValueChanged += new EventHandler(AlgorithmType_ValueChanged);
200      ProblemTypeParameter.ValueChanged += new EventHandler(ProblemTypeParameter_ValueChanged);
201      ProblemType.ValueChanged += new EventHandler(ProblemType_ValueChanged);
202      Problems.ItemsAdded += new Collections.CollectionItemsChangedEventHandler<Collections.IndexedItem<IProblem>>(Problems_ItemsAdded);
203      Problems.ItemsRemoved += new Collections.CollectionItemsChangedEventHandler<Collections.IndexedItem<IProblem>>(Problems_ItemsRemoved);
204    }
205
206    private void InitializeOperators() {
207      Operators.AddRange(ApplicationManager.Manager.GetInstances<IParameterConfigurationOperator>().Cast<IOperator>());
208      Operators.Add(new ReferenceQualityAnalyzer());
209      Operators.Add(new BestParameterConfigurationAnalyzer());
210      Operators.Add(new SolutionCacheAnalyzer());
211      Operators.Add(new PMOPopulationDiversityAnalyzer());
212      Operators.Add(new PMOProblemQualitiesAnalyzer());
213      Operators.Add(new PMOBestSolutionHistoryAnalyzer());
214      Operators.Add(new PopulationAnalyzer());
215    }
216    private void ParameterizeSolutionCreator() {
217    }
218    private void ParameterizeEvaluator() {
219      ((PMOEvaluator)Evaluator).ParameterConfigurationParameter.ActualName = ((RandomParameterConfigurationCreator)SolutionCreator).ParameterConfigurationParameter.ActualName;
220    }
221    private void ParameterizeAnalyzer() {
222      if (BestParameterConfigurationAnalyzer != null) {
223        BestParameterConfigurationAnalyzer.ParameterConfigurationParameter.ActualName = ((RandomParameterConfigurationCreator)SolutionCreator).ParameterConfigurationParameter.ActualName;
224      }
225      if (ReferenceQualityAnalyzer != null) {
226        ReferenceQualityAnalyzer.ParameterConfigurationParameter.ActualName = ((RandomParameterConfigurationCreator)SolutionCreator).ParameterConfigurationParameter.ActualName;
227      }
228      if (RunsAnalyzer != null) {
229        RunsAnalyzer.ParameterConfigurationParameter.ActualName = ((RandomParameterConfigurationCreator)SolutionCreator).ParameterConfigurationParameter.ActualName;
230      }
231      if (PMOPopulationDiversityAnalyzer != null) {
232        PMOPopulationDiversityAnalyzer.SolutionParameter.ActualName = ((RandomParameterConfigurationCreator)SolutionCreator).ParameterConfigurationParameter.ActualName;
233        PMOPopulationDiversityAnalyzer.StoreHistoryParameter.Value.Value = true;
234      }
235      if (PMOProblemQualitiesAnalyzer != null) {
236        PMOProblemQualitiesAnalyzer.ParameterConfigurationParameter.ActualName = ((RandomParameterConfigurationCreator)SolutionCreator).ParameterConfigurationParameter.ActualName;
237      }
238      if (PMOBestSolutionHistoryAnalyzer != null) {
239        PMOBestSolutionHistoryAnalyzer.ParameterConfigurationParameter.ActualName = ((RandomParameterConfigurationCreator)SolutionCreator).ParameterConfigurationParameter.ActualName;
240      }
241    }
242    private void ParameterizeOperators() {
243      foreach (IParameterConfigurationCrossover op in Operators.OfType<IParameterConfigurationCrossover>()) {
244        op.ParentsParameter.ActualName = ((RandomParameterConfigurationCreator)SolutionCreator).ParameterConfigurationParameter.ActualName;
245        op.ChildParameter.ActualName = ((RandomParameterConfigurationCreator)SolutionCreator).ParameterConfigurationParameter.ActualName;
246      }
247      foreach (IParameterConfigurationManipulator op in Operators.OfType<IParameterConfigurationManipulator>()) {
248        op.ParameterConfigurationTreeParameter.ActualName = ((RandomParameterConfigurationCreator)SolutionCreator).ParameterConfigurationParameter.ActualName;
249      }
250    }
251
252    #endregion
253
254    #region Events
255
256    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
257      ParameterizeSolutionCreator();
258      ParameterizeEvaluator();
259      ParameterizeAnalyzer();
260      ParameterizeOperators();
261      OnSolutionCreatorChanged();
262    }
263    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
264      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
265      ParameterizeEvaluator();
266      ParameterizeAnalyzer();
267      OnEvaluatorChanged();
268    }
269    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
270      ParameterizeAnalyzer();
271    }
272    private void AlgorithmTypeParameter_ValueChanged(object sender, EventArgs e) {
273      AlgorithmType_ValueChanged(sender, e);
274    }
275
276    private void AlgorithmType_ValueChanged(object sender, EventArgs e) {
277      IAlgorithm instance = (IAlgorithm)Activator.CreateInstance(AlgorithmType.Value);
278      this.ProblemType.ValidTypes = ApplicationManager.Manager.GetTypes(instance.ProblemType, true).ToList();
279      var newProblemType = this.ProblemType.ValidTypes.SingleOrDefault(t => t == typeof(SingleObjectiveTestFunctionProblem)) ?? this.ProblemType.ValidTypes.Where(t => t != typeof(MetaOptimizationProblem)).FirstOrDefault();
280      if (this.ProblemType.Value != newProblemType)
281        this.ProblemType.Value = newProblemType; // ProblemType_ValueChanged will add one problem and create ParameterConfigurationTree
282      else
283        ProblemType_ValueChanged(this, EventArgs.Empty); // call explicitly
284    }
285
286    private void ProblemTypeParameter_ValueChanged(object sender, EventArgs e) {
287      ProblemType_ValueChanged(sender, e);
288    }
289
290    private void ProblemType_ValueChanged(object sender, EventArgs e) {
291      Problems.Clear();
292      Problems.Type = ProblemType.Value;
293      Problems.Add((IProblem)Activator.CreateInstance(this.ProblemType.Value));
294    }
295
296    private void Problems_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IProblem>> e) {
297      // the first problem in the list is always the instance for the algorithm - this way some basic wiring between problem and algorithm can be sustained
298      if (e.Items.Single().Index == 0) {
299        ParameterConfigurationTreeParameter.ActualValue = new ParameterConfigurationTree(CreateAlgorithm(AlgorithmType.Value, e.Items.Single().Value), e.Items.Single().Value);
300
301        // special for DataAnalysisProblem: Because of wiring between algorithm and problem, ParameterConfigurationTree needs to be recreated on Reset event
302        var dap = e.Items.Single().Value as IDataAnalysisProblem;
303        if (dap != null) {
304          dap.Reset += new EventHandler(DataAnalysisProblem_Reset);
305        }
306      }
307    }
308
309    private void Problems_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<IProblem>> e) {
310      if (e.Items.Single().Index == 0) {
311        ParameterConfigurationTreeParameter.ActualValue = null;
312
313        var dap = e.Items.Single().Value as IDataAnalysisProblem;
314        if (dap != null) {
315          dap.Reset -= new EventHandler(DataAnalysisProblem_Reset);
316        }
317      }
318    }
319
320    private void DataAnalysisProblem_Reset(object sender, EventArgs e) {
321      ParameterConfigurationTreeParameter.ActualValue = new ParameterConfigurationTree(CreateAlgorithm(AlgorithmType.Value, Problems.First()), Problems.First());
322    }
323    #endregion
324
325    private IAlgorithm CreateAlgorithm(Type algorithmType, IProblem problem) {
326      IAlgorithm algorithm = (IAlgorithm)Activator.CreateInstance(algorithmType);
327      algorithm.Problem = problem;
328      return algorithm;
329    }
330
331    public void ImportAlgorithm(IAlgorithm algorithm) {
332      AlgorithmType.Value = algorithm.GetType();
333      if (algorithm.Problem != null) ProblemType.Value = algorithm.Problem.GetType();
334      if (algorithm.Problem != null) {
335        Problems.Clear();
336        Problems.Add((IProblem)algorithm.Problem);
337      }
338      ParameterConfigurationTreeParameter.ActualValue = new ParameterConfigurationTree(algorithm, Problems.First());
339    }
340  }
341}
Note: See TracBrowser for help on using the repository browser.