Free cookie consent management tool by TermsFeed Policy Generator

source: addons/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/MetaOptimizationProblem.cs @ 16574

Last change on this file since 16574 was 16574, checked in by gkronber, 5 years ago

#2520: changed HeuristicLab.MetaOptimization addon to compile with new HL.Persistence

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