Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.MultiObjectiveTestFunctions/HeuristicLab.Problems.MultiObjectiveTestFunctions/3.3/MultiObjectiveTestFunctionProblem.cs @ 13725

Last change on this file since 13725 was 13725, checked in by bwerth, 8 years ago

#1087 minor bugfixes, added Parameters to Analyzers, convenience Tooltips for ScatterPlot

File size: 11.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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
21using System;
22using System.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.RealVectorEncoding;
28using HeuristicLab.Optimization;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Problems.Instances;
32
33namespace HeuristicLab.Problems.MultiObjectiveTestFunctions {
34  [StorableClass]
35  public class MultiObjectiveTestFunctionProblem : MultiObjectiveBasicProblem<RealVectorEncoding>, IProblemInstanceConsumer<MOTFData> {
36
37    #region Parameter Properties
38
39    /// <summary>
40    /// Whether an objective is to be maximized or minimized
41    /// </summary>
42    private IValueParameter<BoolArray> MaximizationParameter {
43      get {
44        return (IValueParameter<BoolArray>)Parameters["Maximization"];
45      }
46      set {
47        Parameters["Maximization"].ActualValue = value;
48      }
49    }
50
51    /// <summary>
52    /// The dimensionality of the solution candidates
53    /// </summary>
54    private IFixedValueParameter<IntValue> ProblemSizeParameter {
55      get { return (IFixedValueParameter<IntValue>)Parameters["ProblemSize"]; }
56    }
57
58    /// <summary>
59    /// The number of objectives that are to be optimized
60    /// </summary>
61    private IFixedValueParameter<IntValue> ObjectivesParameter {
62      get { return (IFixedValueParameter<IntValue>)Parameters["Objectives"]; }
63    }
64
65    /// <summary>
66    /// The bounds for the entries of the solution candidate
67    /// </summary>
68    private IValueParameter<DoubleMatrix> BoundsParameter {
69      get { return (IValueParameter<DoubleMatrix>)Parameters["Bounds"]; }
70    }
71
72    /// <summary>
73    /// The testfunction
74    /// </summary>
75    public IValueParameter<IMultiObjectiveTestFunction> TestFunctionParameter {
76      get { return (IValueParameter<IMultiObjectiveTestFunction>)Parameters["TestFunction"]; }
77    }
78
79    /// <summary>
80    /// The testfunction
81    /// </summary>
82    public IValueParameter<DoubleArray> ReferencePointParameter {
83      get { return (IValueParameter<DoubleArray>)Parameters["ReferencePoint"]; }
84    }
85
86    public IValueParameter<DoubleMatrix> BestKnownFrontParameter {
87      get {
88        return (IValueParameter<DoubleMatrix>)Parameters["BestKnownFront"];
89      }
90    }
91
92    #endregion
93
94    #region Properties
95    private IEnumerable<IMultiObjectiveTestFunctionAnalyzer> Analyzers {
96      get { return Operators.OfType<IMultiObjectiveTestFunctionAnalyzer>(); }
97    }
98
99    public int ProblemSize {
100      get { return ProblemSizeParameter.Value.Value; }
101      set { ProblemSizeParameter.Value.Value = value; }
102    }
103    public int Objectives {
104      get { return ObjectivesParameter.Value.Value; }
105      set { ObjectivesParameter.Value.Value = value; }
106    }
107    public DoubleMatrix Bounds {
108      get { return BoundsParameter.Value; }
109      set { BoundsParameter.Value = value; }
110    }
111    public IMultiObjectiveTestFunction TestFunction {
112      get { return TestFunctionParameter.Value; }
113      set { TestFunctionParameter.Value = value; }
114    }
115    #endregion
116
117    [StorableConstructor]
118    private MultiObjectiveTestFunctionProblem(bool deserializing) : base(deserializing) { }
119    private MultiObjectiveTestFunctionProblem(MultiObjectiveTestFunctionProblem original, Cloner cloner)
120      : base(original, cloner) {
121      RegisterEventHandlers();
122    }
123    public MultiObjectiveTestFunctionProblem()
124      : base() {
125      Parameters.Remove("Maximization");
126      Parameters.Add(new ValueParameter<BoolArray>("Maximization", "", new BoolArray(new bool[] { false, false })));
127      Parameters.Add(new FixedValueParameter<IntValue>("ProblemSize", "The dimensionality of the problem instance (number of variables in the function).", new IntValue(2)));
128      Parameters.Add(new FixedValueParameter<IntValue>("Objectives", "The dimensionality of the solution vector (number of objectives).", new IntValue(2)));
129      Parameters.Add(new ValueParameter<DoubleMatrix>("Bounds", "The bounds of the solution given as either one line for all variables or a line for each variable. The first column specifies lower bound, the second upper bound.", new DoubleMatrix(new double[,] { { -4, 4 } })));
130      Parameters.Add(new ValueParameter<IMultiObjectiveTestFunction>("TestFunction", "The function that is to be optimized.", new Fonseca()));
131      Parameters.Add(new ValueParameter<DoubleMatrix>("BestKnownFront", "The currently best known Pareto front"));
132
133      Encoding.LengthParameter = ProblemSizeParameter;
134      Encoding.BoundsParameter = BoundsParameter;
135      BestKnownFrontParameter.Hidden = true;
136
137      InitializeOperators();
138      RegisterEventHandlers();
139    }
140    public override IDeepCloneable Clone(Cloner cloner) {
141      return new MultiObjectiveTestFunctionProblem(this, cloner);
142    }
143    [StorableHook(HookType.AfterDeserialization)]
144    private void AfterDeserialization() {
145      RegisterEventHandlers();
146    }
147
148    public override void Analyze(Individual[] individuals, double[][] qualities, ResultCollection results, IRandom random) {
149      base.Analyze(individuals, qualities, results, random);
150      if (results.ContainsKey("Pareto Front")) {
151        ((DoubleMatrix)results["Pareto Front"].Value).SortableView = true;
152      }
153      //DoubleMatrix res = (DoubleMatrix)results["Pareto Front"];
154      //res.SortableView = true;
155    }
156
157    public override bool[] Maximization {
158      get {
159        return Parameters.ContainsKey("TestFunction") ? TestFunction.Maximization(Objectives) : new bool[2];
160      }
161    }
162
163    public double[] Evaluate(RealVector individual, IRandom random) {
164      return TestFunction.Evaluate(individual, Objectives);
165    }
166
167    public override double[] Evaluate(Individual individual, IRandom random) {
168      return Evaluate(individual.RealVector(), random);
169    }
170
171    public void Load(MOTFData data) {
172      TestFunction = data.Evaluator;
173    }
174
175    private void RegisterEventHandlers() {
176      TestFunctionParameter.ValueChanged += TestFunctionParameterOnValueChanged;
177      ProblemSizeParameter.Value.ValueChanged += ProblemSizeOnValueChanged;
178      ObjectivesParameter.Value.ValueChanged += ObjectivesOnValueChanged;
179      BoundsParameter.ValueChanged += BoundsParameterOnValueChanged;
180    }
181
182    #region Events
183    protected override void OnEncodingChanged() {
184      base.OnEncodingChanged();
185      Parameterize();
186      ParameterizeAnalyzers();
187    }
188    protected override void OnEvaluatorChanged() {
189      base.OnEvaluatorChanged();
190      Parameterize();
191      ParameterizeAnalyzers();
192    }
193
194    private void TestFunctionParameterOnValueChanged(object sender, EventArgs eventArgs) {
195      var problemSizeChange = ProblemSize < TestFunction.MinimumSolutionLength
196                              || ProblemSize > TestFunction.MaximumSolutionLength;
197      if (problemSizeChange) {
198        ProblemSize = Math.Max(TestFunction.MinimumSolutionLength, Math.Min(ProblemSize, TestFunction.MaximumSolutionLength));
199      }
200
201      var solutionSizeChange = Objectives < TestFunction.MinimumObjectives
202                              || Objectives > TestFunction.MaximumObjectives;
203      if (solutionSizeChange) {
204        ProblemSize = Math.Max(TestFunction.MinimumObjectives, Math.Min(Objectives, TestFunction.MaximumObjectives));
205      }
206
207      Bounds = (DoubleMatrix)new DoubleMatrix(TestFunction.Bounds(Objectives)).Clone();
208      ParameterizeAnalyzers();
209      Parameterize();
210      OnReset();
211    }
212
213    private void ProblemSizeOnValueChanged(object sender, EventArgs eventArgs) {
214      if (ProblemSize < TestFunction.MinimumSolutionLength
215        || ProblemSize > TestFunction.MaximumSolutionLength)
216        ProblemSize = Math.Min(TestFunction.MaximumSolutionLength, Math.Max(TestFunction.MinimumSolutionLength, ProblemSize));
217      if (Objectives < TestFunction.MinimumObjectives
218        || Objectives > TestFunction.MaximumObjectives)
219        Objectives = Math.Min(TestFunction.MaximumObjectives, Math.Max(TestFunction.MinimumObjectives, Objectives));
220      Parameterize();
221    }
222
223    private void ObjectivesOnValueChanged(object sender, EventArgs eventArgs) {
224      if (Objectives < TestFunction.MinimumObjectives
225        || Objectives > TestFunction.MaximumObjectives)
226        Objectives = Math.Min(TestFunction.MaximumObjectives, Math.Max(TestFunction.MinimumObjectives, Objectives));
227      if (ProblemSize < TestFunction.MinimumSolutionLength
228        || ProblemSize > TestFunction.MaximumSolutionLength)
229        ProblemSize = Math.Min(TestFunction.MaximumSolutionLength, Math.Max(TestFunction.MinimumSolutionLength, ProblemSize));
230      Parameterize();
231    }
232
233    private void BoundsParameterOnValueChanged(object sender, EventArgs eventArgs) {
234      Parameterize();
235    }
236    #endregion
237
238    #region Helpers
239    private void InitializeOperators() {
240      Operators.Add(new CrowdingAnalyzer());
241      Operators.Add(new GenerationalDistanceAnalyzer());
242      Operators.Add(new InvertedGenerationalDistanceAnalyzer());
243      Operators.Add(new HypervolumeAnalyzer());
244      Operators.Add(new SpacingAnalyzer());
245      Operators.Add(new ScatterPlotAnalyzer());
246      ParameterizeAnalyzers();
247      Parameterize();
248    }
249
250    private void Parameterize() {
251      MaximizationParameter.ActualValue = new BoolArray(Maximization);
252    }
253
254    private void ParameterizeAnalyzers() {
255      foreach (var analyzer in Analyzers) {
256        analyzer.ResultsParameter.ActualName = "Results";
257        analyzer.QualitiesParameter.ActualName = Evaluator.QualitiesParameter.ActualName;
258        analyzer.TestFunctionParameter.ActualName = TestFunctionParameter.Name;
259        analyzer.BestKnownFrontParameter.ActualName = BestKnownFrontParameter.Name;
260
261        BestKnownFrontParameter.ActualValue = new DoubleMatrix(To2D(TestFunction.OptimalParetoFront(Objectives).ToArray<double[]>()));
262        if (analyzer is HypervolumeAnalyzer) {
263          ((HypervolumeAnalyzer)analyzer).ReferencePointParameter.Value = new DoubleArray(TestFunction.ReferencePoint(Objectives));
264          ((HypervolumeAnalyzer)analyzer).BestKnownHyperVolumeParameter.Value = new DoubleValue(TestFunction.BestKnownHypervolume(Objectives));
265        }
266
267      }
268    }
269
270    public static T[,] To2D<T>(T[][] source) {
271      try {
272        int FirstDim = source.Length;
273        int SecondDim = source.GroupBy(row => row.Length).Single().Key; // throws InvalidOperationException if source is not rectangular
274
275        var result = new T[FirstDim, SecondDim];
276        for (int i = 0; i < FirstDim; ++i)
277          for (int j = 0; j < SecondDim; ++j)
278            result[i, j] = source[i][j];
279
280        return result;
281      }
282      catch (InvalidOperationException) {
283        throw new InvalidOperationException("The given jagged array is not rectangular.");
284      }
285    }
286
287    #endregion
288  }
289}
290
Note: See TracBrowser for help on using the repository browser.