Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Problems.TestFunctions/3.3/SingleObjectiveTestFunctionProblem.cs @ 17695

Last change on this file since 17695 was 17695, checked in by abeham, 4 years ago

#2521:

  • Moving solution creator parameter from problems to algorithms (breaking wiring in some HeuristicOptimizationProblems)
  • Disallowing evaluator or encoding changes in encoding-specific base problems (to avoid confusion in derived problems whether this needs to be handled or not)
  • Added private set to ReferenceParameter property (serialization)
File size: 7.8 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
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Threading;
26using HEAL.Attic;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Encodings.RealVectorEncoding;
31using HeuristicLab.Optimization;
32using HeuristicLab.Parameters;
33using HeuristicLab.Problems.Instances;
34
35namespace HeuristicLab.Problems.TestFunctions {
36  [Item("Test Function (single-objective)", "Test function with real valued inputs and a single objective.")]
37  [StorableType("F0AB7236-2C9B-49DC-9D4F-A3558FD9E992")]
38  [Creatable(CreatableAttribute.Categories.Problems, Priority = 90)]
39  public sealed class SingleObjectiveTestFunctionProblem : RealVectorProblem,
40    IProblemInstanceConsumer<SOTFData> {
41
42    #region Parameter Properties
43    public OptionalValueParameter<RealVector> BestKnownSolutionParameter {
44      get { return (OptionalValueParameter<RealVector>)Parameters["BestKnownSolution"]; }
45    }
46    public IValueParameter<ISingleObjectiveTestFunction> TestFunctionParameter {
47      get { return (IValueParameter<ISingleObjectiveTestFunction>)Parameters["TestFunction"]; }
48    }
49    #endregion
50
51    #region Properties
52    public ISingleObjectiveTestFunction TestFunction {
53      get { return TestFunctionParameter.Value; }
54      set { TestFunctionParameter.Value = value; }
55    }
56    #endregion
57
58    [StorableConstructor]
59    private SingleObjectiveTestFunctionProblem(StorableConstructorFlag _) : base(_) { }
60    private SingleObjectiveTestFunctionProblem(SingleObjectiveTestFunctionProblem original, Cloner cloner)
61      : base(original, cloner) {
62      RegisterEventHandlers();
63    }
64    public SingleObjectiveTestFunctionProblem()
65      : base(new RealVectorEncoding("Point")) {
66      Parameters.Add(new OptionalValueParameter<RealVector>("BestKnownSolution", "The best known solution for this test function instance."));
67      Parameters.Add(new ValueParameter<ISingleObjectiveTestFunction>("TestFunction", "The function that is to be optimized.", new Ackley()));
68      Maximization = TestFunction.Maximization;
69
70      BestKnownQuality = TestFunction.BestKnownQuality;
71      Bounds = (DoubleMatrix)TestFunction.Bounds.Clone();
72      Dimension = Math.Min(Math.Max(2, TestFunction.MinimumProblemSize), TestFunction.MaximumProblemSize);
73      BestKnownSolutionParameter.Value = TestFunction.GetBestKnownSolution(Dimension);
74
75
76      Operators.AddRange(new IItem[] {
77        new SingleObjectiveTestFunctionImprovementOperator(),
78        new SingleObjectiveTestFunctionPathRelinker(),
79        new SingleObjectiveTestFunctionSimilarityCalculator(),
80        new EuclideanSimilarityCalculator(),
81        new AdditiveMoveEvaluator() });
82
83      Parameterize();
84      RegisterEventHandlers();
85    }
86
87    public override IDeepCloneable Clone(Cloner cloner) {
88      return new SingleObjectiveTestFunctionProblem(this, cloner);
89    }
90
91    [StorableHook(HookType.AfterDeserialization)]
92    private void AfterDeserialization() {
93      RegisterEventHandlers();
94    }
95
96    private void RegisterEventHandlers() {
97      TestFunctionParameter.ValueChanged += TestFunctionParameterOnValueChanged;
98    }
99
100    public override ISingleObjectiveEvaluationResult Evaluate(RealVector individual, IRandom random, CancellationToken cancellationToken) {
101      var quality = TestFunction.Evaluate(individual);
102      return new SingleObjectiveEvaluationResult(quality);
103    }
104
105    public override void Analyze(RealVector[] realVectors, double[] qualities, ResultCollection results, IRandom random) {
106      var best = GetBestSolution(realVectors, qualities);
107
108      DoubleValue bestKnownQuality = BestKnownQualityParameter.Value;
109      RealVector bestKnownSolution = null;
110      var bestKnownUpdate = bestKnownQuality == null || IsBetter(best.Item2, bestKnownQuality.Value);
111      if (bestKnownUpdate) {
112        if (bestKnownQuality != null) bestKnownQuality.Value = best.Item2;
113        else BestKnownQualityParameter.Value = bestKnownQuality = new DoubleValue(best.Item2);
114        BestKnownSolutionParameter.Value = bestKnownSolution = (RealVector)best.Item1.Clone();
115      }
116
117      SingleObjectiveTestFunctionSolution solution = null;
118      if (results.TryGetValue("Best Solution", out var res) && res.Value != null) {
119        solution = (SingleObjectiveTestFunctionSolution)res.Value;
120        if (IsBetter(best.Item2, solution.BestQuality.Value)) {
121          solution.BestRealVector = (RealVector)best.Item1.Clone();
122          solution.BestQuality = new DoubleValue(best.Item2);
123        }
124      } else {
125        solution = new SingleObjectiveTestFunctionSolution((RealVector)best.Item1.Clone(),
126                                                           new DoubleValue(best.Item2),
127                                                           TestFunctionParameter.Value) {
128          BestKnownRealVector = bestKnownSolution,
129          Bounds = BoundsRefParameter.Value
130        };
131        results.AddOrUpdateResult("Best Solution", solution);
132      }
133      if (best.Item1.Length == 2) solution.Population = new ItemArray<RealVector>(realVectors.Select(x => (RealVector)x.Clone()));
134      if (bestKnownUpdate) solution.BestKnownRealVector = bestKnownSolution;
135    }
136
137    #region Events
138    protected override void ParameterizeOperators() {
139      base.ParameterizeOperators();
140      Parameterize();
141    }
142    protected override void DimensionOnChanged() {
143      base.DimensionOnChanged();
144      if (Dimension < TestFunction.MinimumProblemSize || Dimension > TestFunction.MaximumProblemSize)
145        Dimension = Math.Min(TestFunction.MaximumProblemSize, Math.Max(TestFunction.MinimumProblemSize, Dimension));
146    }
147    protected override void BoundsOnChanged() {
148      base.BoundsOnChanged();
149      Parameterize();
150    }
151    private void TestFunctionParameterOnValueChanged(object sender, EventArgs eventArgs) {
152      var problemSizeChange = Dimension < TestFunction.MinimumProblemSize
153                              || Dimension > TestFunction.MaximumProblemSize;
154      if (problemSizeChange) {
155        Dimension = Math.Max(TestFunction.MinimumProblemSize, Math.Min(Dimension, TestFunction.MaximumProblemSize));
156      }
157      BestKnownQuality = TestFunction.BestKnownQuality;
158      Bounds = (DoubleMatrix)TestFunction.Bounds.Clone();
159      var bestSolution = TestFunction.GetBestKnownSolution(Dimension);
160      BestKnownSolutionParameter.Value = bestSolution;
161      Maximization = TestFunction.Maximization;
162
163      OnReset();
164    }
165    #endregion
166
167    #region Helpers
168    private void Parameterize() {
169      var operators = new List<IItem>();
170
171      foreach (var op in Operators.OfType<ITestFunctionSolutionSimilarityCalculator>()) {
172        operators.Add(op);
173        op.Bounds = Bounds;
174      }
175
176      if (operators.Count > 0) Encoding.ConfigureOperators(operators);
177    }
178    #endregion
179
180    public void Load(SOTFData data) {
181      Name = data.Name;
182      Description = data.Description;
183      TestFunction = data.TestFunction;
184    }
185  }
186}
Note: See TracBrowser for help on using the repository browser.