Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2943_MOBasicProblem_MOCMAES/HeuristicLab.Problems.TestFunctions.MultiObjective/3.3/MultiObjectiveTestFunctionProblem.cs @ 16674

Last change on this file since 16674 was 16310, checked in by bwerth, 6 years ago

#2943 worked on MOBasicProblem and MOAnalyzers

File size: 10.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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.TestFunctions.MultiObjective {
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 new IValueParameter<BoolArray> MaximizationParameter {
41      get { return (IValueParameter<BoolArray>)Parameters[MaximizationParameterName]; }
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
56    #endregion
57
58    #region Properties
59    public override bool[] Maximization {
60      get{ return Parameters.ContainsKey(MaximizationParameterName) ? MaximizationParameter.Value.CloneAsArray() : new Fonseca().Maximization(2); }
61    }
62
63    public int ProblemSize {
64      get { return ProblemSizeParameter.Value.Value; }
65      set { ProblemSizeParameter.Value.Value = value; }
66    }
67    public int Objectives {
68      get { return ObjectivesParameter.Value.Value; }
69      set { ObjectivesParameter.Value.Value = value; }
70    }
71    public DoubleMatrix Bounds {
72      get { return BoundsParameter.Value; }
73      set { BoundsParameter.Value = value; }
74    }
75    public IMultiObjectiveTestFunction TestFunction {
76      get { return TestFunctionParameter.Value; }
77      set { TestFunctionParameter.Value = value; }
78    }
79    #endregion
80
81    [StorableConstructor]
82    protected MultiObjectiveTestFunctionProblem(bool deserializing) : base(deserializing) { }
83    [StorableHook(HookType.AfterDeserialization)]
84    private void AfterDeserialization() {
85      RegisterEventHandlers();
86    }
87
88    protected MultiObjectiveTestFunctionProblem(MultiObjectiveTestFunctionProblem original, Cloner cloner) : base(original, cloner) {
89      RegisterEventHandlers();
90    }
91    public override IDeepCloneable Clone(Cloner cloner) {
92      return new MultiObjectiveTestFunctionProblem(this, cloner);
93    }
94
95    public MultiObjectiveTestFunctionProblem() : base() {
96      Parameters.Add(new FixedValueParameter<IntValue>("ProblemSize", "The dimensionality of the problem instance (number of variables in the function).", new IntValue(2)));
97      Parameters.Add(new FixedValueParameter<IntValue>("Objectives", "The dimensionality of the solution vector (number of objectives).", new IntValue(2)));
98      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 } })));
99      Parameters.Add(new ValueParameter<IMultiObjectiveTestFunction>("TestFunction", "The function that is to be optimized.", new Fonseca()));
100
101      Encoding.LengthParameter = ProblemSizeParameter;
102      Encoding.BoundsParameter = BoundsParameter;
103      BestKnownFrontParameter.Hidden = true;
104
105      UpdateParameterValues();
106      InitializeOperators();
107      RegisterEventHandlers();
108    }
109
110    private void RegisterEventHandlers() {
111      TestFunctionParameter.ValueChanged += TestFunctionParameterOnValueChanged;
112      ProblemSizeParameter.Value.ValueChanged += ProblemSizeOnValueChanged;
113      ObjectivesParameter.Value.ValueChanged += ObjectivesOnValueChanged;
114    }
115
116
117    public override void Analyze(Individual[] individuals, double[][] qualities, ResultCollection results, IRandom random) {
118      base.Analyze(individuals, qualities, results, random);
119      if (results.ContainsKey("Pareto Front"))
120        ((DoubleMatrix)results["Pareto Front"].Value).SortableView = true;
121    }
122
123    /// <summary>
124    /// Checks whether a given solution violates the contraints of this function.
125    /// </summary>
126    /// <param name="individual"></param>
127    /// <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>
128    public double[] CheckContraints(RealVector individual) {
129      var constrainedTestFunction = (IConstrainedTestFunction)TestFunction;
130      return constrainedTestFunction != null ? constrainedTestFunction.CheckConstraints(individual, Objectives) : new double[0];
131    }
132
133    public double[] Evaluate(RealVector individual) {
134      return TestFunction.Evaluate(individual, Objectives);
135    }
136
137    public override double[] Evaluate(Individual individual, IRandom random) {
138      return Evaluate(individual.RealVector());
139    }
140
141    public void Load(MOTFData data) {
142      TestFunction = data.TestFunction;
143    }
144
145    #region Events
146    private void UpdateParameterValues() {
147      Parameters.Remove(MaximizationParameterName);
148      Parameters.Add(new FixedValueParameter<BoolArray>(MaximizationParameterName, "Set to false if the problem should be minimized.", (BoolArray)new BoolArray(TestFunction.Maximization(Objectives)).AsReadOnly()));
149
150      Parameters.Remove(BestKnownFrontParameterName);
151      var front = TestFunction.OptimalParetoFront(Objectives);
152      var bkf = front != null ? (DoubleMatrix)Utilities.ToMatrix(front).AsReadOnly() : null;
153      Parameters.Add(new FixedValueParameter<DoubleMatrix>(BestKnownFrontParameterName, "A double matrix representing the best known qualites for this problem (aka points on the Pareto front). Points are to be given in a row-wise fashion.", bkf));
154
155      Parameters.Remove(ReferencePointParameterName);
156      Parameters.Add(new FixedValueParameter<DoubleArray>(ReferencePointParameterName, "The refrence point for hypervolume calculations on this problem", new DoubleArray(TestFunction.ReferencePoint(Objectives))));
157
158      BoundsParameter.Value = new DoubleMatrix(TestFunction.Bounds(Objectives));
159    }
160
161    protected override void OnEncodingChanged() {
162      base.OnEncodingChanged();
163      UpdateParameterValues();
164      ParameterizeAnalyzers();
165    }
166
167    protected override void OnEvaluatorChanged() {
168      base.OnEvaluatorChanged();
169      UpdateParameterValues();
170      ParameterizeAnalyzers();
171    }
172
173    private void TestFunctionParameterOnValueChanged(object sender, EventArgs eventArgs) {
174      ProblemSize = Math.Max(TestFunction.MinimumSolutionLength, Math.Min(ProblemSize, TestFunction.MaximumSolutionLength));
175      Objectives = Math.Max(TestFunction.MinimumObjectives, Math.Min(Objectives, TestFunction.MaximumObjectives));
176      Parameters.Remove(ReferencePointParameterName);
177      Parameters.Add(new FixedValueParameter<DoubleArray>(ReferencePointParameterName, "The refrence point for hypervolume calculations on this problem", new DoubleArray(TestFunction.ReferencePoint(Objectives))));
178      ParameterizeAnalyzers();
179      UpdateParameterValues();
180      OnReset();
181    }
182
183    private void ProblemSizeOnValueChanged(object sender, EventArgs eventArgs) {
184      ProblemSize = Math.Min(TestFunction.MaximumSolutionLength, Math.Max(TestFunction.MinimumSolutionLength, ProblemSize));
185      UpdateParameterValues();
186    }
187
188    private void ObjectivesOnValueChanged(object sender, EventArgs eventArgs) {
189      Objectives = Math.Min(TestFunction.MaximumObjectives, Math.Max(TestFunction.MinimumObjectives, Objectives));
190      UpdateParameterValues();
191    }
192
193    #endregion
194
195    #region Helpers
196    private void InitializeOperators() {
197      Operators.Add(new Analysis.CrowdingAnalyzer());
198      Operators.Add(new Analysis.GenerationalDistanceAnalyzer());
199      Operators.Add(new Analysis.InvertedGenerationalDistanceAnalyzer());
200      Operators.Add(new Analysis.HypervolumeAnalyzer());
201      Operators.Add(new Analysis.SpacingAnalyzer());
202      Operators.Add(new Analysis.TimelineAnalyzer());
203      Operators.Add(new ScatterPlotAnalyzer());
204      ParameterizeAnalyzers();
205    }
206
207    private IEnumerable<IMultiObjectiveTestFunctionAnalyzer> Analyzers => Operators.OfType<IMultiObjectiveTestFunctionAnalyzer>();
208
209    private void ParameterizeAnalyzers() {
210      foreach (var analyzer in Analyzers) {
211        analyzer.ResultsParameter.ActualName = "Results";
212        analyzer.QualitiesParameter.ActualName = Evaluator.QualitiesParameter.ActualName;
213        analyzer.TestFunctionParameter.ActualName = TestFunctionParameter.Name;
214        analyzer.BestKnownFrontParameter.ActualName = BestKnownFrontParameter.Name;
215        if (analyzer is ScatterPlotAnalyzer scatterPlotAnalyzer)
216          scatterPlotAnalyzer.IndividualsParameter.ActualName = Encoding.Name;
217      }
218    }
219    #endregion
220  }
221}
222
Note: See TracBrowser for help on using the repository browser.