source: branches/2521_ProblemRefactoring/HeuristicLab.Problems.TestFunctions.MultiObjective/3.3/MultiObjectiveTestFunctionProblem.cs @ 17320

Last change on this file since 17320 was 17320, checked in by mkommend, 9 months ago

#2521: Added cancellation token to evaluate function of problems.

File size: 8.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.Threading;
23using HEAL.Attic;
24using HeuristicLab.Analysis;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.RealVectorEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Problems.Instances;
32
33namespace HeuristicLab.Problems.TestFunctions.MultiObjective {
34  [StorableType("AB0C6A73-C432-46FD-AE3B-9841EAB2478C")]
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 : RealVectorMultiObjectiveProblem, IProblemInstanceConsumer<MOTFData>, IMultiObjectiveProblemDefinition<RealVectorEncoding, RealVector> {
38    #region Parameter Properties
39    public IFixedValueParameter<IntValue> ProblemSizeParameter {
40      get { return (IFixedValueParameter<IntValue>)Parameters["ProblemSize"]; }
41    }
42    public IFixedValueParameter<IntValue> ObjectivesParameter {
43      get { return (IFixedValueParameter<IntValue>)Parameters["Objectives"]; }
44    }
45    public IValueParameter<DoubleMatrix> BoundsParameter {
46      get { return (IValueParameter<DoubleMatrix>)Parameters["Bounds"]; }
47    }
48    public IValueParameter<IMultiObjectiveTestFunction> TestFunctionParameter {
49      get { return (IValueParameter<IMultiObjectiveTestFunction>)Parameters["TestFunction"]; }
50    }
51    #endregion
52
53    #region Properties
54    public int ProblemSize {
55      get { return ProblemSizeParameter.Value.Value; }
56      set { ProblemSizeParameter.Value.Value = value; }
57    }
58    public new int Objectives {
59      get { return ObjectivesParameter.Value.Value; }
60      set { ObjectivesParameter.Value.Value = value; }
61    }
62    public DoubleMatrix Bounds {
63      get { return BoundsParameter.Value; }
64      set { BoundsParameter.Value = value; }
65    }
66    public IMultiObjectiveTestFunction TestFunction {
67      get { return TestFunctionParameter.Value; }
68      set { TestFunctionParameter.Value = value; }
69    }
70    #endregion
71
72    [StorableConstructor]
73    protected MultiObjectiveTestFunctionProblem(StorableConstructorFlag _) : base(_) { }
74    [StorableHook(HookType.AfterDeserialization)]
75    private void AfterDeserialization() {
76      RegisterEventHandlers();
77    }
78
79    protected MultiObjectiveTestFunctionProblem(MultiObjectiveTestFunctionProblem original, Cloner cloner) : base(original, cloner) {
80      RegisterEventHandlers();
81    }
82    public override IDeepCloneable Clone(Cloner cloner) {
83      return new MultiObjectiveTestFunctionProblem(this, cloner);
84    }
85
86    public MultiObjectiveTestFunctionProblem() : base() {
87      Parameters.Add(new FixedValueParameter<IntValue>("ProblemSize", "The dimensionality of the problem instance (number of variables in the function).", new IntValue(2)));
88      Parameters.Add(new FixedValueParameter<IntValue>("Objectives", "The dimensionality of the solution vector (number of objectives).", new IntValue(2)));
89      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 } })));
90      Parameters.Add(new ValueParameter<IMultiObjectiveTestFunction>("TestFunction", "The function that is to be optimized.", new Fonseca()));
91
92      Encoding.LengthParameter = ProblemSizeParameter;
93      Encoding.BoundsParameter = BoundsParameter;
94      BestKnownFrontParameter.Hidden = true;
95
96      UpdateParameterValues();
97      InitializeOperators();
98      RegisterEventHandlers();
99    }
100
101    private void RegisterEventHandlers() {
102      TestFunctionParameter.ValueChanged += TestFunctionParameterOnValueChanged;
103      ProblemSizeParameter.Value.ValueChanged += ProblemSizeOnValueChanged;
104      ObjectivesParameter.Value.ValueChanged += ObjectivesOnValueChanged;
105    }
106
107
108    public override void Analyze(RealVector[] solutions, double[][] qualities, ResultCollection results, IRandom random) {
109      base.Analyze(solutions, qualities, results, random);
110      if (results.ContainsKey("Pareto Front"))
111        ((DoubleMatrix)results["Pareto Front"].Value).SortableView = true;
112    }
113
114    /// <summary>
115    /// Checks whether a given solution violates the contraints of this function.
116    /// </summary>
117    /// <param name="individual"></param>
118    /// <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>
119    public double[] CheckContraints(RealVector individual) {
120      var constrainedTestFunction = (IConstrainedTestFunction)TestFunction;
121      return constrainedTestFunction != null ? constrainedTestFunction.CheckConstraints(individual, Objectives) : new double[0];
122    }
123
124    public override double[] Evaluate(RealVector solution, IRandom random, CancellationToken cancellationToken) {
125      return TestFunction.Evaluate(solution, Objectives);
126    }
127
128
129    public void Load(MOTFData data) {
130      TestFunction = data.TestFunction;
131    }
132
133    #region Events
134    private void UpdateParameterValues() {
135      Maximization = TestFunction.Maximization(Objectives);
136
137      Parameters.Remove(BestKnownFrontParameterName);
138      var front = TestFunction.OptimalParetoFront(Objectives);
139      var bkf = front != null ? (DoubleMatrix)Utilities.ToMatrix(front).AsReadOnly() : null;
140      Parameters.Add(new FixedValueParameter<DoubleMatrix>(BestKnownFrontParameterName, "A double matrix representing the best known qualities for this problem (aka points on the Pareto front). Points are to be given in a row-wise fashion.", bkf));
141
142      Parameters.Remove(ReferencePointParameterName);
143      Parameters.Add(new FixedValueParameter<DoubleArray>(ReferencePointParameterName, "The reference point for hypervolume calculations on this problem", new DoubleArray(TestFunction.ReferencePoint(Objectives))));
144
145      BoundsParameter.Value = new DoubleMatrix(TestFunction.Bounds(Objectives));
146    }
147
148    protected override void OnEncodingChanged() {
149      base.OnEncodingChanged();
150      UpdateParameterValues();
151    }
152
153    protected override void OnEvaluatorChanged() {
154      base.OnEvaluatorChanged();
155      UpdateParameterValues();
156    }
157
158    private void TestFunctionParameterOnValueChanged(object sender, EventArgs eventArgs) {
159      ProblemSize = Math.Max(TestFunction.MinimumSolutionLength, Math.Min(ProblemSize, TestFunction.MaximumSolutionLength));
160      Objectives = Math.Max(TestFunction.MinimumObjectives, Math.Min(Objectives, TestFunction.MaximumObjectives));
161      Parameters.Remove(ReferencePointParameterName);
162      Parameters.Add(new FixedValueParameter<DoubleArray>(ReferencePointParameterName, "The reference point for hypervolume calculations on this problem", new DoubleArray(TestFunction.ReferencePoint(Objectives))));
163      UpdateParameterValues();
164      OnReset();
165    }
166
167    private void ProblemSizeOnValueChanged(object sender, EventArgs eventArgs) {
168      ProblemSize = Math.Min(TestFunction.MaximumSolutionLength, Math.Max(TestFunction.MinimumSolutionLength, ProblemSize));
169      UpdateParameterValues();
170    }
171
172    private void ObjectivesOnValueChanged(object sender, EventArgs eventArgs) {
173      Objectives = Math.Min(TestFunction.MaximumObjectives, Math.Max(TestFunction.MinimumObjectives, Objectives));
174      UpdateParameterValues();
175    }
176    #endregion
177
178    #region Helpers
179    private void InitializeOperators() {
180      Operators.Add(new CrowdingAnalyzer());
181      Operators.Add(new GenerationalDistanceAnalyzer());
182      Operators.Add(new InvertedGenerationalDistanceAnalyzer());
183      Operators.Add(new HypervolumeAnalyzer());
184      Operators.Add(new SpacingAnalyzer());
185      Operators.Add(new TimelineAnalyzer());
186    }
187    #endregion
188  }
189}
Note: See TracBrowser for help on using the repository browser.