source: branches/ProblemRefactoring/HeuristicLab.Problems.TestFunctions/3.3/SingleObjectiveTestFunctionProblem.cs @ 13361

Last change on this file since 13361 was 13361, checked in by mkommend, 4 years ago

#2521: Adapted real vector encoding, test function problems, P3, CMA-ES and optimization.

File size: 20.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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 HeuristicLab.Analysis;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.RealVectorEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.PluginInfrastructure;
35using HeuristicLab.Problems.Instances;
36
37namespace HeuristicLab.Problems.TestFunctions {
38  [Item("Test Function (single-objective)", "Test function with real valued inputs and a single objective.")]
39  [StorableClass]
40  [Creatable(CreatableAttribute.Categories.Problems, Priority = 90)]
41  public sealed class SingleObjectiveTestFunctionProblem :
42    SingleObjectiveHeuristicOptimizationProblem<ISingleObjectiveTestFunctionProblemEvaluator, IRealVectorCreator>,
43    ISingleObjectiveProblem<RealVectorEncoding, RealVector>, IStorableContent, IProblemInstanceConsumer<SOTFData> {
44    public string Filename { get; set; }
45
46    [Storable]
47    private StdDevStrategyVectorCreator strategyVectorCreator;
48    [Storable]
49    private StdDevStrategyVectorCrossover strategyVectorCrossover;
50    [Storable]
51    private StdDevStrategyVectorManipulator strategyVectorManipulator;
52
53    #region Parameter Properties
54    public ValueParameter<DoubleMatrix> BoundsParameter {
55      get { return (ValueParameter<DoubleMatrix>)Parameters["Bounds"]; }
56    }
57    public ValueParameter<IntValue> ProblemSizeParameter {
58      get { return (ValueParameter<IntValue>)Parameters["ProblemSize"]; }
59    }
60    public OptionalValueParameter<RealVector> BestKnownSolutionParameter {
61      get { return (OptionalValueParameter<RealVector>)Parameters["BestKnownSolution"]; }
62    }
63    #endregion
64
65    #region Properties
66    public DoubleMatrix Bounds {
67      get { return BoundsParameter.Value; }
68      set { BoundsParameter.Value = value; }
69    }
70    public IntValue ProblemSize {
71      get { return ProblemSizeParameter.Value; }
72      set { ProblemSizeParameter.Value = value; }
73    }
74    private BestSingleObjectiveTestFunctionSolutionAnalyzer BestSingleObjectiveTestFunctionSolutionAnalyzer {
75      get { return Operators.OfType<BestSingleObjectiveTestFunctionSolutionAnalyzer>().FirstOrDefault(); }
76    }
77    #endregion
78
79    // BackwardsCompatibility3.3
80    #region Backwards compatible code, remove with 3.4
81    [Obsolete]
82    [Storable(Name = "operators")]
83    private IEnumerable<IOperator> oldOperators {
84      get { return null; }
85      set {
86        if (value != null && value.Any())
87          Operators.AddRange(value);
88      }
89    }
90    #endregion
91
92    [StorableConstructor]
93    private SingleObjectiveTestFunctionProblem(bool deserializing) : base(deserializing) { }
94    private SingleObjectiveTestFunctionProblem(SingleObjectiveTestFunctionProblem original, Cloner cloner)
95      : base(original, cloner) {
96      strategyVectorCreator = cloner.Clone(original.strategyVectorCreator);
97      strategyVectorCrossover = cloner.Clone(original.strategyVectorCrossover);
98      strategyVectorManipulator = cloner.Clone(original.strategyVectorManipulator);
99      RegisterEventHandlers();
100    }
101    public SingleObjectiveTestFunctionProblem()
102      : base(new AckleyEvaluator(), new UniformRandomRealVectorCreator()) {
103      Parameters.Add(new ValueParameter<DoubleMatrix>("Bounds", "The lower and upper bounds in each dimension.", Evaluator.Bounds));
104      Parameters.Add(new ValueParameter<IntValue>("ProblemSize", "The dimension of the problem.", new IntValue(2)));
105      Parameters.Add(new OptionalValueParameter<RealVector>("BestKnownSolution", "The best known solution for this test function instance."));
106
107      Maximization.Value = Evaluator.Maximization;
108      BestKnownQuality = new DoubleValue(Evaluator.BestKnownQuality);
109
110      strategyVectorCreator = new StdDevStrategyVectorCreator();
111      strategyVectorCreator.LengthParameter.ActualName = ProblemSizeParameter.Name;
112      strategyVectorCrossover = new StdDevStrategyVectorCrossover();
113      strategyVectorManipulator = new StdDevStrategyVectorManipulator();
114      strategyVectorManipulator.LearningRateParameter.Value = new DoubleValue(0.5);
115      strategyVectorManipulator.GeneralLearningRateParameter.Value = new DoubleValue(0.5);
116
117      SolutionCreator.RealVectorParameter.ActualName = "Point";
118      ParameterizeSolutionCreator();
119      ParameterizeEvaluator();
120
121      InitializeOperators();
122      RegisterEventHandlers();
123      UpdateStrategyVectorBounds();
124    }
125
126    public override IDeepCloneable Clone(Cloner cloner) {
127      return new SingleObjectiveTestFunctionProblem(this, cloner);
128    }
129
130    #region Events
131    protected override void OnSolutionCreatorChanged() {
132      base.OnSolutionCreatorChanged();
133      ParameterizeSolutionCreator();
134      ParameterizeAnalyzers();
135      SolutionCreator.RealVectorParameter.ActualNameChanged += new EventHandler(SolutionCreator_RealVectorParameter_ActualNameChanged);
136      SolutionCreator_RealVectorParameter_ActualNameChanged(null, EventArgs.Empty);
137    }
138    protected override void OnEvaluatorChanged() {
139      base.OnEvaluatorChanged();
140      bool problemSizeChange = ProblemSize.Value < Evaluator.MinimumProblemSize
141        || ProblemSize.Value > Evaluator.MaximumProblemSize;
142      if (problemSizeChange) {
143        ProblemSize.Value = Math.Max(Evaluator.MinimumProblemSize, Math.Min(ProblemSize.Value, Evaluator.MaximumProblemSize));
144      } else {
145        ParameterizeEvaluator();
146      }
147      UpdateMoveEvaluators();
148      ParameterizeAnalyzers();
149      Maximization.Value = Evaluator.Maximization;
150      BoundsParameter.Value = Evaluator.Bounds;
151      BestKnownQuality = new DoubleValue(Evaluator.BestKnownQuality);
152      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
153      Evaluator_QualityParameter_ActualNameChanged(null, EventArgs.Empty);
154      OnReset();
155    }
156    private void ProblemSizeParameter_ValueChanged(object sender, EventArgs e) {
157      ProblemSize.ValueChanged += new EventHandler(ProblemSize_ValueChanged);
158      ProblemSize_ValueChanged(null, EventArgs.Empty);
159    }
160    private void ProblemSize_ValueChanged(object sender, EventArgs e) {
161      if (ProblemSize.Value < 1) ProblemSize.Value = 1;
162      ParameterizeSolutionCreator();
163      ParameterizeEvaluator();
164      strategyVectorManipulator.GeneralLearningRateParameter.Value = new DoubleValue(1.0 / Math.Sqrt(2 * ProblemSize.Value));
165      strategyVectorManipulator.LearningRateParameter.Value = new DoubleValue(1.0 / Math.Sqrt(2 * Math.Sqrt(ProblemSize.Value)));
166      OnReset();
167    }
168    private void SolutionCreator_RealVectorParameter_ActualNameChanged(object sender, EventArgs e) {
169      ParameterizeEvaluator();
170      ParameterizeOperators();
171      ParameterizeAnalyzers();
172    }
173    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
174      ParameterizeOperators();
175    }
176    private void BoundsParameter_ValueChanged(object sender, EventArgs e) {
177      Bounds.ToStringChanged += new EventHandler(Bounds_ToStringChanged);
178      Bounds_ToStringChanged(null, EventArgs.Empty);
179    }
180    private void Bounds_ToStringChanged(object sender, EventArgs e) {
181      if (Bounds.Columns != 2 || Bounds.Rows < 1)
182        Bounds = new DoubleMatrix(1, 2);
183      ParameterizeOperators();
184      UpdateStrategyVectorBounds();
185    }
186    private void Bounds_ItemChanged(object sender, EventArgs<int, int> e) {
187      if (e.Value2 == 0 && Bounds[e.Value, 1] <= Bounds[e.Value, 0])
188        Bounds[e.Value, 1] = Bounds[e.Value, 0] + 0.1;
189      if (e.Value2 == 1 && Bounds[e.Value, 0] >= Bounds[e.Value, 1])
190        Bounds[e.Value, 0] = Bounds[e.Value, 1] - 0.1;
191      ParameterizeOperators();
192      UpdateStrategyVectorBounds();
193    }
194    private void MoveGenerator_AdditiveMoveParameter_ActualNameChanged(object sender, EventArgs e) {
195      string name = ((ILookupParameter<AdditiveMove>)sender).ActualName;
196      foreach (IAdditiveRealVectorMoveOperator op in Operators.OfType<IAdditiveRealVectorMoveOperator>()) {
197        op.AdditiveMoveParameter.ActualName = name;
198      }
199    }
200    private void SphereEvaluator_Parameter_ValueChanged(object sender, EventArgs e) {
201      SphereEvaluator eval = (Evaluator as SphereEvaluator);
202      if (eval != null) {
203        foreach (ISphereMoveEvaluator op in Operators.OfType<ISphereMoveEvaluator>()) {
204          op.C = eval.C;
205          op.Alpha = eval.Alpha;
206        }
207      }
208    }
209    private void RastriginEvaluator_Parameter_ValueChanged(object sender, EventArgs e) {
210      RastriginEvaluator eval = (Evaluator as RastriginEvaluator);
211      if (eval != null) {
212        foreach (IRastriginMoveEvaluator op in Operators.OfType<IRastriginMoveEvaluator>()) {
213          op.A = eval.A;
214        }
215      }
216    }
217    private void strategyVectorCreator_BoundsParameter_ValueChanged(object sender, EventArgs e) {
218      strategyVectorManipulator.BoundsParameter.Value = (DoubleMatrix)strategyVectorCreator.BoundsParameter.Value.Clone();
219    }
220    private void strategyVectorCreator_StrategyParameterParameter_ActualNameChanged(object sender, EventArgs e) {
221      string name = strategyVectorCreator.StrategyParameterParameter.ActualName;
222      strategyVectorCrossover.ParentsParameter.ActualName = name;
223      strategyVectorCrossover.StrategyParameterParameter.ActualName = name;
224      strategyVectorManipulator.StrategyParameterParameter.ActualName = name;
225    }
226    #endregion
227
228    #region Helpers
229    [StorableHook(HookType.AfterDeserialization)]
230    private void AfterDeserialization() {
231      // BackwardsCompatibility3.3
232      #region Backwards compatible code (remove with 3.4)
233      if (Operators.Count == 0) InitializeOperators();
234      #endregion
235      RegisterEventHandlers();
236    }
237
238    private void RegisterEventHandlers() {
239      ProblemSizeParameter.ValueChanged += new EventHandler(ProblemSizeParameter_ValueChanged);
240      ProblemSize.ValueChanged += new EventHandler(ProblemSize_ValueChanged);
241      BoundsParameter.ValueChanged += new EventHandler(BoundsParameter_ValueChanged);
242      Bounds.ToStringChanged += new EventHandler(Bounds_ToStringChanged);
243      Bounds.ItemChanged += new EventHandler<EventArgs<int, int>>(Bounds_ItemChanged);
244      SolutionCreator.RealVectorParameter.ActualNameChanged += new EventHandler(SolutionCreator_RealVectorParameter_ActualNameChanged);
245      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
246      strategyVectorCreator.BoundsParameter.ValueChanged += new EventHandler(strategyVectorCreator_BoundsParameter_ValueChanged);
247      strategyVectorCreator.StrategyParameterParameter.ActualNameChanged += new EventHandler(strategyVectorCreator_StrategyParameterParameter_ActualNameChanged);
248    }
249    private void ParameterizeAnalyzers() {
250      if (BestSingleObjectiveTestFunctionSolutionAnalyzer != null) {
251        BestSingleObjectiveTestFunctionSolutionAnalyzer.RealVectorParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
252        BestSingleObjectiveTestFunctionSolutionAnalyzer.ResultsParameter.ActualName = "Results";
253        BestSingleObjectiveTestFunctionSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
254        BestSingleObjectiveTestFunctionSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
255        BestSingleObjectiveTestFunctionSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
256        BestSingleObjectiveTestFunctionSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
257        BestSingleObjectiveTestFunctionSolutionAnalyzer.EvaluatorParameter.ActualName = EvaluatorParameter.Name;
258        BestSingleObjectiveTestFunctionSolutionAnalyzer.BoundsParameter.ActualName = BoundsParameter.Name;
259      }
260    }
261    private void InitializeOperators() {
262      Operators.Add(new SingleObjectiveTestFunctionImprovementOperator());
263      Operators.Add(new SingleObjectiveTestFunctionPathRelinker());
264      Operators.Add(new SingleObjectiveTestFunctionSimilarityCalculator());
265      Operators.Add(new QualitySimilarityCalculator());
266      Operators.Add(new NoSimilarityCalculator());
267
268      Operators.Add(new BestSingleObjectiveTestFunctionSolutionAnalyzer());
269      Operators.Add(new PopulationSimilarityAnalyzer(Operators.OfType<ISolutionSimilarityCalculator>()));
270      ParameterizeAnalyzers();
271      Operators.AddRange(ApplicationManager.Manager.GetInstances<IRealVectorOperator>().Cast<IOperator>());
272      Operators.Add(strategyVectorCreator);
273      Operators.Add(strategyVectorCrossover);
274      Operators.Add(strategyVectorManipulator);
275      UpdateMoveEvaluators();
276      ParameterizeOperators();
277      InitializeMoveGenerators();
278    }
279    private void InitializeMoveGenerators() {
280      foreach (IAdditiveRealVectorMoveOperator op in Operators.OfType<IAdditiveRealVectorMoveOperator>()) {
281        if (op is IMoveGenerator) {
282          op.AdditiveMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_AdditiveMoveParameter_ActualNameChanged);
283        }
284      }
285    }
286    private void UpdateMoveEvaluators() {
287      foreach (ISingleObjectiveTestFunctionMoveEvaluator op in Operators.OfType<ISingleObjectiveTestFunctionMoveEvaluator>().ToList())
288        Operators.Remove(op);
289      foreach (ISingleObjectiveTestFunctionMoveEvaluator op in ApplicationManager.Manager.GetInstances<ISingleObjectiveTestFunctionMoveEvaluator>())
290        if (op.EvaluatorType == Evaluator.GetType()) {
291          Operators.Add(op);
292          #region Synchronize evaluator specific parameters with the parameters of the corresponding move evaluators
293          if (op is ISphereMoveEvaluator) {
294            SphereEvaluator e = (Evaluator as SphereEvaluator);
295            e.AlphaParameter.ValueChanged += new EventHandler(SphereEvaluator_Parameter_ValueChanged);
296            e.CParameter.ValueChanged += new EventHandler(SphereEvaluator_Parameter_ValueChanged);
297            ISphereMoveEvaluator em = (op as ISphereMoveEvaluator);
298            em.C = e.C;
299            em.Alpha = e.Alpha;
300          } else if (op is IRastriginMoveEvaluator) {
301            RastriginEvaluator e = (Evaluator as RastriginEvaluator);
302            e.AParameter.ValueChanged += new EventHandler(RastriginEvaluator_Parameter_ValueChanged);
303            IRastriginMoveEvaluator em = (op as IRastriginMoveEvaluator);
304            em.A = e.A;
305          }
306          #endregion
307        }
308      ParameterizeOperators();
309      OnOperatorsChanged();
310    }
311    private void ParameterizeSolutionCreator() {
312      SolutionCreator.LengthParameter.Value = new IntValue(ProblemSize.Value);
313      SolutionCreator.LengthParameter.Hidden = true;
314      SolutionCreator.BoundsParameter.ActualName = BoundsParameter.Name;
315      SolutionCreator.BoundsParameter.Hidden = true;
316    }
317    private void ParameterizeEvaluator() {
318      Evaluator.PointParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
319      Evaluator.PointParameter.Hidden = true;
320      try {
321        BestKnownSolutionParameter.Value = Evaluator.GetBestKnownSolution(ProblemSize.Value);
322      }
323      catch (ArgumentException e) {
324        ErrorHandling.ShowErrorDialog(e);
325        ProblemSize.Value = Evaluator.MinimumProblemSize;
326      }
327    }
328    private void ParameterizeOperators() {
329      foreach (var op in Operators.OfType<IRealVectorCrossover>()) {
330        op.ParentsParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
331        op.ParentsParameter.Hidden = true;
332        op.ChildParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
333        op.ChildParameter.Hidden = true;
334        op.BoundsParameter.ActualName = BoundsParameter.Name;
335        op.BoundsParameter.Hidden = true;
336      }
337      foreach (var op in Operators.OfType<IRealVectorManipulator>()) {
338        op.RealVectorParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
339        op.RealVectorParameter.Hidden = true;
340        op.BoundsParameter.ActualName = BoundsParameter.Name;
341        op.BoundsParameter.Hidden = true;
342      }
343      foreach (var op in Operators.OfType<IRealVectorMoveOperator>()) {
344        op.RealVectorParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
345        op.RealVectorParameter.Hidden = true;
346      }
347      foreach (var op in Operators.OfType<IRealVectorMoveGenerator>()) {
348        op.BoundsParameter.ActualName = BoundsParameter.Name;
349        op.BoundsParameter.Hidden = true;
350      }
351      foreach (var op in Operators.OfType<ISingleObjectiveTestFunctionAdditiveMoveEvaluator>()) {
352        op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
353        op.QualityParameter.Hidden = true;
354        op.RealVectorParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
355        op.RealVectorParameter.Hidden = true;
356      }
357      foreach (var op in Operators.OfType<IRealVectorParticleCreator>()) {
358        op.RealVectorParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
359        op.RealVectorParameter.Hidden = true;
360        op.BoundsParameter.ActualName = BoundsParameter.Name;
361        op.BoundsParameter.Hidden = true;
362        op.ProblemSizeParameter.ActualName = ProblemSizeParameter.Name;
363        op.ProblemSizeParameter.Hidden = true;
364      }
365      foreach (var op in Operators.OfType<IRealVectorParticleUpdater>()) {
366        op.RealVectorParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
367        op.RealVectorParameter.Hidden = true;
368        op.BoundsParameter.ActualName = BoundsParameter.Name;
369        op.BoundsParameter.Hidden = true;
370      }
371      foreach (var op in Operators.OfType<IRealVectorSwarmUpdater>()) {
372        op.RealVectorParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
373        op.RealVectorParameter.Hidden = true;
374        op.MaximizationParameter.ActualName = MaximizationParameter.Name;
375        op.MaximizationParameter.Hidden = true;
376      }
377      foreach (var op in Operators.OfType<IRealVectorMultiNeighborhoodShakingOperator>()) {
378        op.RealVectorParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
379        op.RealVectorParameter.Hidden = true;
380      }
381      foreach (var op in Operators.OfType<ISingleObjectiveImprovementOperator>()) {
382        op.SolutionParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
383        op.SolutionParameter.Hidden = true;
384      }
385      foreach (var op in Operators.OfType<ISingleObjectivePathRelinker>()) {
386        op.ParentsParameter.ActualName = SolutionCreator.RealVectorParameter.ActualName;
387        op.ParentsParameter.Hidden = true;
388      }
389      foreach (var op in Operators.OfType<ISolutionSimilarityCalculator>()) {
390        op.SolutionVariableName = SolutionCreator.RealVectorParameter.ActualName;
391        op.QualityVariableName = Evaluator.QualityParameter.ActualName;
392        var calc = op as SingleObjectiveTestFunctionSimilarityCalculator;
393        if (calc != null) calc.Bounds = Bounds;
394      }
395    }
396    private void UpdateStrategyVectorBounds() {
397      var strategyBounds = (DoubleMatrix)Bounds.Clone();
398      for (int i = 0; i < strategyBounds.Rows; i++) {
399        if (strategyBounds[i, 0] < 0) strategyBounds[i, 0] = 0;
400        strategyBounds[i, 1] = 0.1 * (Bounds[i, 1] - Bounds[i, 0]);
401      }
402      strategyVectorCreator.BoundsParameter.Value = strategyBounds;
403    }
404    #endregion
405
406    public void Load(SOTFData data) {
407      Name = data.Name;
408      Description = data.Description;
409      Evaluator = data.Evaluator;
410    }
411  }
412}
Note: See TracBrowser for help on using the repository browser.