Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1087 several fixes according to the reviev comments in comment 31

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