Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1087 bugfix + additional relative HV calculation added

File size: 12.3 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    protected MultiObjectiveTestFunctionProblem(bool deserializing) : base(deserializing) { }
119    protected 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 IEnumerable<double[]> BestKnownFront {
164      get {
165        return Parameters.ContainsKey("BestKnownFront") ? TestFunction.OptimalParetoFront(Objectives) : null;
166      }
167    }
168
169    public double[] Evaluate(RealVector individual, IRandom random) {
170      return TestFunction.Evaluate(individual, Objectives);
171    }
172
173    public override double[] Evaluate(Individual individual, IRandom random) {
174      return Evaluate(individual.RealVector(), random);
175    }
176
177    public void Load(MOTFData data) {
178      TestFunction = data.Evaluator;
179    }
180
181    private void RegisterEventHandlers() {
182      TestFunctionParameter.ValueChanged += TestFunctionParameterOnValueChanged;
183      ProblemSizeParameter.Value.ValueChanged += ProblemSizeOnValueChanged;
184      ObjectivesParameter.Value.ValueChanged += ObjectivesOnValueChanged;
185      BoundsParameter.ValueChanged += BoundsParameterOnValueChanged;
186    }
187
188    #region Events
189    protected override void OnEncodingChanged() {
190      base.OnEncodingChanged();
191      Parameterize();
192      ParameterizeAnalyzers();
193    }
194    protected override void OnEvaluatorChanged() {
195      base.OnEvaluatorChanged();
196      Parameterize();
197      ParameterizeAnalyzers();
198    }
199
200    private void TestFunctionParameterOnValueChanged(object sender, EventArgs eventArgs) {
201      var problemSizeChange = ProblemSize < TestFunction.MinimumSolutionLength
202                              || ProblemSize > TestFunction.MaximumSolutionLength;
203      if (problemSizeChange) {
204        ProblemSize = Math.Max(TestFunction.MinimumSolutionLength, Math.Min(ProblemSize, TestFunction.MaximumSolutionLength));
205      }
206
207      var solutionSizeChange = Objectives < TestFunction.MinimumObjectives
208                              || Objectives > TestFunction.MaximumObjectives;
209      if (solutionSizeChange) {
210        ProblemSize = Math.Max(TestFunction.MinimumObjectives, Math.Min(Objectives, TestFunction.MaximumObjectives));
211      }
212
213      Bounds = (DoubleMatrix)new DoubleMatrix(TestFunction.Bounds(Objectives)).Clone();
214      ParameterizeAnalyzers();
215      Parameterize();
216      OnReset();
217    }
218
219    private void ProblemSizeOnValueChanged(object sender, EventArgs eventArgs) {
220      if (ProblemSize < TestFunction.MinimumSolutionLength
221        || ProblemSize > TestFunction.MaximumSolutionLength)
222        ProblemSize = Math.Min(TestFunction.MaximumSolutionLength, Math.Max(TestFunction.MinimumSolutionLength, ProblemSize));
223      if (Objectives < TestFunction.MinimumObjectives
224        || Objectives > TestFunction.MaximumObjectives)
225        Objectives = Math.Min(TestFunction.MaximumObjectives, Math.Max(TestFunction.MinimumObjectives, Objectives));
226      Parameterize();
227    }
228
229    private void ObjectivesOnValueChanged(object sender, EventArgs eventArgs) {
230      if (Objectives < TestFunction.MinimumObjectives
231        || Objectives > TestFunction.MaximumObjectives)
232        Objectives = Math.Min(TestFunction.MaximumObjectives, Math.Max(TestFunction.MinimumObjectives, Objectives));
233      if (ProblemSize < TestFunction.MinimumSolutionLength
234        || ProblemSize > TestFunction.MaximumSolutionLength)
235        ProblemSize = Math.Min(TestFunction.MaximumSolutionLength, Math.Max(TestFunction.MinimumSolutionLength, ProblemSize));
236
237
238      Parameterize();
239    }
240
241    private void BoundsParameterOnValueChanged(object sender, EventArgs eventArgs) {
242      Parameterize();
243    }
244    #endregion
245
246    #region Helpers
247    private void InitializeOperators() {
248      Operators.Add(new CrowdingAnalyzer());
249      Operators.Add(new GenerationalDistanceAnalyzer());
250      Operators.Add(new InvertedGenerationalDistanceAnalyzer());
251      Operators.Add(new HypervolumeAnalyzer());
252      Operators.Add(new SpacingAnalyzer());
253      Operators.Add(new ScatterPlotAnalyzer());
254      Operators.Add(new NormalizedHypervolumeAnalyzer());
255      ParameterizeAnalyzers();
256      Parameterize();
257    }
258
259    private void Parameterize() {
260      MaximizationParameter.ActualValue = new BoolArray(Maximization);
261      var front = BestKnownFront;
262      if (front != null) { BestKnownFrontParameter.ActualValue = new DoubleMatrix(To2D(front.ToArray<double[]>())); }
263
264    }
265
266    private void ParameterizeAnalyzers() {
267      foreach (var analyzer in Analyzers) {
268        analyzer.ResultsParameter.ActualName = "Results";
269        analyzer.QualitiesParameter.ActualName = Evaluator.QualitiesParameter.ActualName;
270        analyzer.TestFunctionParameter.ActualName = TestFunctionParameter.Name;
271        analyzer.BestKnownFrontParameter.ActualName = BestKnownFrontParameter.Name;
272
273
274        var front = BestKnownFront;
275        if (front != null) { BestKnownFrontParameter.ActualValue = new DoubleMatrix(To2D(front.ToArray<double[]>())); }
276
277
278        if (analyzer is HypervolumeAnalyzer) {
279          ((HypervolumeAnalyzer)analyzer).ReferencePointParameter.Value = new DoubleArray(TestFunction.ReferencePoint(Objectives));
280          ((HypervolumeAnalyzer)analyzer).BestKnownHyperVolumeParameter.Value = new DoubleValue(TestFunction.BestKnownHypervolume(Objectives));
281        }
282
283        if (analyzer is NormalizedHypervolumeAnalyzer) {
284          ((NormalizedHypervolumeAnalyzer)analyzer).OptimalFrontParameter.ActualValue = (DoubleMatrix)BestKnownFrontParameter.ActualValue;
285        }
286
287      }
288    }
289
290    public static T[,] To2D<T>(T[][] source) {
291      try {
292        int FirstDim = source.Length;
293        int SecondDim = source.GroupBy(row => row.Length).Single().Key; // throws InvalidOperationException if source is not rectangular
294
295        var result = new T[FirstDim, SecondDim];
296        for (int i = 0; i < FirstDim; ++i)
297          for (int j = 0; j < SecondDim; ++j)
298            result[i, j] = source[i][j];
299
300        return result;
301      }
302      catch (InvalidOperationException) {
303        throw new InvalidOperationException("The given jagged array is not rectangular.");
304      }
305    }
306
307    #endregion
308  }
309}
310
Note: See TracBrowser for help on using the repository browser.