Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1087: Worked on Multi-objective test function problem and adapted plugin dependencies.

File size: 11.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  [Creatable(CreatableAttribute.Categories.Problems, Priority = 95)]
36  [Item("Test Function (multi-objective)", "Test functions with real valued inputs and multiple objectives.")]
37  public class MultiObjectiveTestFunctionProblem : MultiObjectiveBasicProblem<RealVectorEncoding>, IProblemInstanceConsumer<MOTFData> {
38
39    #region Parameter Properties
40    public IValueParameter<BoolArray> MaximizationParameter {
41      get { return (IValueParameter<BoolArray>)Parameters["Maximization"]; }
42    }
43    public IFixedValueParameter<IntValue> ProblemSizeParameter {
44      get { return (IFixedValueParameter<IntValue>)Parameters["ProblemSize"]; }
45    }
46    public IFixedValueParameter<IntValue> ObjectivesParameter {
47      get { return (IFixedValueParameter<IntValue>)Parameters["Objectives"]; }
48    }
49    public IValueParameter<DoubleMatrix> BoundsParameter {
50      get { return (IValueParameter<DoubleMatrix>)Parameters["Bounds"]; }
51    }
52    public IValueParameter<IMultiObjectiveTestFunction> TestFunctionParameter {
53      get { return (IValueParameter<IMultiObjectiveTestFunction>)Parameters["TestFunction"]; }
54    }
55    public IValueParameter<DoubleArray> ReferencePointParameter {
56      get { return (IValueParameter<DoubleArray>)Parameters["ReferencePoint"]; }
57    }
58    public IValueParameter<DoubleMatrix> BestKnownFrontParameter {
59      get { return (IValueParameter<DoubleMatrix>)Parameters["BestKnownFront"]; }
60    }
61
62    #endregion
63
64    #region Properties
65    public override bool[] Maximization {
66      get {
67        //necessary because of virtual member call in base ctor to this property
68        if (!Parameters.ContainsKey("TestFunction")) return new bool[2];
69        return TestFunction.Maximization(Objectives);
70      }
71    }
72
73    public int ProblemSize {
74      get { return ProblemSizeParameter.Value.Value; }
75      set { ProblemSizeParameter.Value.Value = value; }
76    }
77    public int Objectives {
78      get { return ObjectivesParameter.Value.Value; }
79      set { ObjectivesParameter.Value.Value = value; }
80    }
81    public DoubleMatrix Bounds {
82      get { return BoundsParameter.Value; }
83      set { BoundsParameter.Value = value; }
84    }
85    public IMultiObjectiveTestFunction TestFunction {
86      get { return TestFunctionParameter.Value; }
87      set { TestFunctionParameter.Value = value; }
88    }
89    public IEnumerable<double[]> BestKnownFront {
90      get { return Parameters.ContainsKey("BestKnownFront") ? TestFunction.OptimalParetoFront(Objectives) : null; }
91    }
92    #endregion
93
94    [StorableConstructor]
95    protected MultiObjectiveTestFunctionProblem(bool deserializing) : base(deserializing) { }
96    [StorableHook(HookType.AfterDeserialization)]
97    private void AfterDeserialization() {
98      RegisterEventHandlers();
99    }
100
101    protected MultiObjectiveTestFunctionProblem(MultiObjectiveTestFunctionProblem original, Cloner cloner)
102      : base(original, cloner) {
103      RegisterEventHandlers();
104    }
105    public override IDeepCloneable Clone(Cloner cloner) {
106      return new MultiObjectiveTestFunctionProblem(this, cloner);
107    }
108
109    public MultiObjectiveTestFunctionProblem()
110      : base() {
111      Parameters.Add(new FixedValueParameter<IntValue>("ProblemSize", "The dimensionality of the problem instance (number of variables in the function).", new IntValue(2)));
112      Parameters.Add(new FixedValueParameter<IntValue>("Objectives", "The dimensionality of the solution vector (number of objectives).", new IntValue(2)));
113      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 } })));
114      Parameters.Add(new ValueParameter<IMultiObjectiveTestFunction>("TestFunction", "The function that is to be optimized.", new Fonseca()));
115      Parameters.Add(new ValueParameter<DoubleMatrix>("BestKnownFront", "The currently best known Pareto front"));
116
117      Encoding.LengthParameter = ProblemSizeParameter;
118      Encoding.BoundsParameter = BoundsParameter;
119      BestKnownFrontParameter.Hidden = true;
120
121      UpdateParameterValues();
122      InitializeOperators();
123      RegisterEventHandlers();
124    }
125
126    private void RegisterEventHandlers() {
127      TestFunctionParameter.ValueChanged += TestFunctionParameterOnValueChanged;
128      ProblemSizeParameter.Value.ValueChanged += ProblemSizeOnValueChanged;
129      ObjectivesParameter.Value.ValueChanged += ObjectivesOnValueChanged;
130    }
131
132
133    public override void Analyze(Individual[] individuals, double[][] qualities, ResultCollection results, IRandom random) {
134      base.Analyze(individuals, qualities, results, random);
135      if (results.ContainsKey("Pareto Front")) {
136        ((DoubleMatrix)results["Pareto Front"].Value).SortableView = true;
137      }
138    }
139
140    /// <summary>
141    /// Checks whether a given solution violates the contraints of this function.
142    /// </summary>
143    /// <param name="individual"></param>
144    /// <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>
145    public double[] CheckContraints(RealVector individual) {
146      var constrainedTestFunction = (IConstrainedTestFunction)TestFunction;
147      if (constrainedTestFunction != null) {
148        return constrainedTestFunction.CheckConstraints(individual, Objectives);
149      }
150      return new double[0];
151    }
152
153    public double[] Evaluate(RealVector individual) {
154      return TestFunction.Evaluate(individual, Objectives);
155    }
156
157    public override double[] Evaluate(Individual individual, IRandom random) {
158      return Evaluate(individual.RealVector());
159    }
160
161    public void Load(MOTFData data) {
162      TestFunction = data.TestFunction;
163    }
164
165    #region Events
166    private void UpdateParameterValues() {
167      MaximizationParameter.ActualValue = (BoolArray)new BoolArray(Maximization).AsReadOnly();
168      var front = BestKnownFront;
169      if (front != null) { BestKnownFrontParameter.Value = (DoubleMatrix)new DoubleMatrix(To2D(front.ToArray())).AsReadOnly(); }
170
171    }
172
173    protected override void OnEncodingChanged() {
174      base.OnEncodingChanged();
175      UpdateParameterValues();
176      ParameterizeAnalyzers();
177    }
178    protected override void OnEvaluatorChanged() {
179      base.OnEvaluatorChanged();
180      UpdateParameterValues();
181      ParameterizeAnalyzers();
182    }
183
184    private void TestFunctionParameterOnValueChanged(object sender, EventArgs eventArgs) {
185      ProblemSize = Math.Max(TestFunction.MinimumSolutionLength, Math.Min(ProblemSize, TestFunction.MaximumSolutionLength));
186      Objectives = Math.Max(TestFunction.MinimumObjectives, Math.Min(Objectives, TestFunction.MaximumObjectives));
187
188      Bounds = (DoubleMatrix)new DoubleMatrix(TestFunction.Bounds(Objectives)).Clone();
189      ParameterizeAnalyzers();
190      UpdateParameterValues();
191      OnReset();
192    }
193
194    private void ProblemSizeOnValueChanged(object sender, EventArgs eventArgs) {
195      ProblemSize = Math.Min(TestFunction.MaximumSolutionLength, Math.Max(TestFunction.MinimumSolutionLength, ProblemSize));
196      UpdateParameterValues();
197    }
198
199    private void ObjectivesOnValueChanged(object sender, EventArgs eventArgs) {
200      Objectives = Math.Min(TestFunction.MaximumObjectives, Math.Max(TestFunction.MinimumObjectives, Objectives));
201      UpdateParameterValues();
202    }
203
204    #endregion
205
206    #region Helpers
207    private void InitializeOperators() {
208      Operators.Add(new CrowdingAnalyzer());
209      Operators.Add(new GenerationalDistanceAnalyzer());
210      Operators.Add(new InvertedGenerationalDistanceAnalyzer());
211      Operators.Add(new HypervolumeAnalyzer());
212      Operators.Add(new SpacingAnalyzer());
213      Operators.Add(new ScatterPlotAnalyzer());
214      Operators.Add(new NormalizedHypervolumeAnalyzer());
215
216      ParameterizeAnalyzers();
217    }
218
219    private IEnumerable<IMultiObjectiveTestFunctionAnalyzer> Analyzers {
220      get { return Operators.OfType<IMultiObjectiveTestFunctionAnalyzer>(); }
221    }
222
223    private void ParameterizeAnalyzers() {
224      foreach (var analyzer in Analyzers) {
225        analyzer.ResultsParameter.ActualName = "Results";
226        analyzer.QualitiesParameter.ActualName = Evaluator.QualitiesParameter.ActualName;
227        analyzer.TestFunctionParameter.ActualName = TestFunctionParameter.Name;
228        analyzer.BestKnownFrontParameter.ActualName = BestKnownFrontParameter.Name;
229
230        var hyperVolumeAnalyzer = analyzer as HypervolumeAnalyzer;
231        if (hyperVolumeAnalyzer != null) {
232          hyperVolumeAnalyzer.ReferencePointParameter.Value = new DoubleArray(TestFunction.ReferencePoint(Objectives));
233          hyperVolumeAnalyzer.BestKnownHyperVolume = TestFunction.BestKnownHypervolume(Objectives);
234        }
235
236        var normalizedHyperVolumeAnalyzer = analyzer as NormalizedHypervolumeAnalyzer;
237        if (normalizedHyperVolumeAnalyzer != null) {
238          normalizedHyperVolumeAnalyzer.OptimalFrontParameter.Value = (DoubleMatrix)BestKnownFrontParameter.ActualValue;
239        }
240
241        var scatterPlotAnalyzer = analyzer as ScatterPlotAnalyzer;
242        if (scatterPlotAnalyzer != null) {
243          scatterPlotAnalyzer.IndividualsParameter.ActualName = Encoding.Name;
244        }
245      }
246    }
247
248    public static T[,] To2D<T>(T[][] source) {
249      try {
250        int firstDimension = source.Length;
251        int secondDimension = source.GroupBy(row => row.Length).Single().Key; // throws InvalidOperationException if source is not rectangular
252
253        var result = new T[firstDimension, secondDimension];
254        for (int i = 0; i < firstDimension; ++i)
255          for (int j = 0; j < secondDimension; ++j)
256            result[i, j] = source[i][j];
257
258        return result;
259      }
260      catch (InvalidOperationException) {
261        throw new InvalidOperationException("The given jagged array is not rectangular.");
262      }
263    }
264
265    #endregion
266  }
267}
268
Note: See TracBrowser for help on using the repository browser.