Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14068 was 14068, checked in by mkommend, 8 years ago

#1087: Added checks for min and max objectives to testfunctions.

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