Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Optimization/3.3/BasicProblems/SingleObjectiveProblem.cs @ 17620

Last change on this file since 17620 was 17612, checked in by mkommend, 4 years ago

#2521: Added first version of problem results.

File size: 10.2 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.Parameters;
31
32namespace HeuristicLab.Optimization {
33  [StorableType("2697320D-0259-44BB-BD71-7EE1B10F664C")]
34  public abstract class SingleObjectiveProblem<TEncoding, TEncodedSolution> :
35    Problem<TEncoding, TEncodedSolution, SingleObjectiveEvaluator<TEncodedSolution>>,
36    ISingleObjectiveProblem<TEncoding, TEncodedSolution>,
37    ISingleObjectiveProblemDefinition<TEncoding, TEncodedSolution>
38    where TEncoding : class, IEncoding<TEncodedSolution>
39    where TEncodedSolution : class, IEncodedSolution {
40
41    [Storable] protected IValueParameter<DoubleValue> BestKnownQualityParameter { get; private set; }
42    [Storable] protected IValueParameter<BoolValue> MaximizationParameter { get; private set; }
43
44    public double BestKnownQuality {
45      get {
46        if (BestKnownQualityParameter.Value == null) return double.NaN;
47        return BestKnownQualityParameter.Value.Value;
48      }
49      set {
50        if (double.IsNaN(value)) {
51          BestKnownQualityParameter.Value = null;
52          return;
53        }
54        if (BestKnownQualityParameter.Value == null) BestKnownQualityParameter.Value = new DoubleValue(value);
55        else BestKnownQualityParameter.Value.Value = value;
56      }
57    }
58
59    public bool Maximization {
60      get { return MaximizationParameter.Value.Value; }
61      protected set {
62        if (Maximization == value) return;
63        MaximizationParameter.Value = new BoolValue(value, @readonly: true);
64      }
65    }
66
67    [StorableConstructor]
68    protected SingleObjectiveProblem(StorableConstructorFlag _) : base(_) { }
69
70    protected SingleObjectiveProblem(SingleObjectiveProblem<TEncoding, TEncodedSolution> original, Cloner cloner)
71      : base(original, cloner) {
72      BestKnownQualityParameter = cloner.Clone(original.BestKnownQualityParameter);
73      MaximizationParameter = cloner.Clone(original.MaximizationParameter);
74      Parameterize();
75      RegisterEventHandlers();
76    }
77
78    protected SingleObjectiveProblem(TEncoding encoding) : base(encoding) {
79      Parameters.Add(MaximizationParameter = new ValueParameter<BoolValue>("Maximization", "Set to false if the problem should be minimized.", new BoolValue(false).AsReadOnly()) { Hidden = true, ReadOnly = true });
80      Parameters.Add(BestKnownQualityParameter = new OptionalValueParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this problem."));
81
82      Operators.Add(Evaluator);
83      Operators.Add(new SingleObjectiveAnalyzer<TEncodedSolution>());
84      Operators.Add(new SingleObjectiveImprover<TEncodedSolution>());
85      Operators.Add(new SingleObjectiveMoveEvaluator<TEncodedSolution>());
86      Operators.Add(new SingleObjectiveMoveGenerator<TEncodedSolution>());
87      Operators.Add(new SingleObjectiveMoveMaker<TEncodedSolution>());
88
89      Parameterize();
90      RegisterEventHandlers();
91    }
92
93    [StorableHook(HookType.AfterDeserialization)]
94    private void AfterDeserialization() {
95      Parameterize();
96      RegisterEventHandlers();
97    }
98
99    public ISingleObjectiveEvaluationResult Evaluate(TEncodedSolution solution, IRandom random) {
100      return Evaluate(solution, random, CancellationToken.None);
101    }
102    public abstract ISingleObjectiveEvaluationResult Evaluate(TEncodedSolution solution, IRandom random, CancellationToken cancellationToken);
103
104    public void Evaluate(ISingleObjectiveSolutionContext<TEncodedSolution> solutionContext, IRandom random) {
105      Evaluate(solutionContext, random, CancellationToken.None);
106    }
107    public virtual void Evaluate(ISingleObjectiveSolutionContext<TEncodedSolution> solutionContext, IRandom random, CancellationToken cancellationToken) {
108      var evaluationResult = Evaluate(solutionContext.EncodedSolution, random, cancellationToken);
109      solutionContext.EvaluationResult = evaluationResult;
110    }
111
112    public virtual void Analyze(TEncodedSolution[] solutions, double[] qualities, ResultCollection results, IRandom random) { }
113    public virtual void Analyze(ISingleObjectiveSolutionContext<TEncodedSolution>[] solutionContexts, ResultCollection results, IRandom random) {
114      var solutions = solutionContexts.Select(c => c.EncodedSolution).ToArray();
115      var qualities = solutionContexts.Select(c => c.EvaluationResult.Quality).ToArray();
116      Analyze(solutions, qualities, results, random);
117    }
118
119    public virtual IEnumerable<TEncodedSolution> GetNeighbors(TEncodedSolution solutions, IRandom random) {
120      return Enumerable.Empty<TEncodedSolution>();
121    }
122    public virtual IEnumerable<ISingleObjectiveSolutionContext<TEncodedSolution>> GetNeighbors(ISingleObjectiveSolutionContext<TEncodedSolution> solutionContext, IRandom random) {
123      return GetNeighbors(solutionContext.EncodedSolution, random).Select(n => new SingleObjectiveSolutionContext<TEncodedSolution>(n));
124    }
125
126    public static bool IsBetter(bool maximization, double quality, double bestQuality) {
127      return (maximization && quality > bestQuality || !maximization && quality < bestQuality);
128    }
129
130    public virtual bool IsBetter(double quality, double bestQuality) {
131      return IsBetter(Maximization, quality, bestQuality);
132    }
133
134    public virtual bool IsBetter(ISingleObjectiveSolutionContext<TEncodedSolution> solution, ISingleObjectiveSolutionContext<TEncodedSolution> otherSolution) {
135      return IsBetter(Maximization, solution.EvaluationResult.Quality, otherSolution.EvaluationResult.Quality);
136    }
137
138    //TODO refactor to solution contexts
139    protected ISingleObjectiveSolutionContext<TEncodedSolution> GetBest(ISingleObjectiveSolutionContext<TEncodedSolution>[] solutionContexts) {
140      return Maximization ? solutionContexts.MaxItems(x => x.EvaluationResult.Quality).First()
141        : solutionContexts.MinItems(x => x.EvaluationResult.Quality).First();
142    }
143    protected Tuple<TEncodedSolution, double> GetBestSolution(TEncodedSolution[] solutions, double[] qualities) {
144      return GetBestSolution(solutions, qualities, Maximization);
145    }
146    public static Tuple<TEncodedSolution, double> GetBestSolution(TEncodedSolution[] solutions, double[] qualities, bool maximization) {
147      var zipped = solutions.Zip(qualities, (s, q) => new { Solution = s, Quality = q });
148      var best = (maximization ? zipped.OrderByDescending(z => z.Quality) : zipped.OrderBy(z => z.Quality)).First();
149      return Tuple.Create(best.Solution, best.Quality);
150    }
151
152    protected override void OnOperatorsChanged() {
153      if (Encoding != null) {
154        PruneMultiObjectiveOperators(Encoding);
155        var combinedEncoding = Encoding as CombinedEncoding;
156        if (combinedEncoding != null) {
157          foreach (var encoding in combinedEncoding.Encodings.ToList()) {
158            PruneMultiObjectiveOperators(encoding);
159          }
160        }
161      }
162      base.OnOperatorsChanged();
163    }
164
165    private void PruneMultiObjectiveOperators(IEncoding encoding) {
166      if (encoding.Operators.Any(x => x is IMultiObjectiveOperator && !(x is ISingleObjectiveOperator)))
167        encoding.Operators = encoding.Operators.Where(x => !(x is IMultiObjectiveOperator) || x is ISingleObjectiveOperator).ToList();
168
169      foreach (var multiOp in Encoding.Operators.OfType<IMultiOperator>()) {
170        foreach (var moOp in multiOp.Operators.Where(x => x is IMultiObjectiveOperator).ToList()) {
171          multiOp.RemoveOperator(moOp);
172        }
173      }
174    }
175
176    protected override void OnEvaluatorChanged() {
177      base.OnEvaluatorChanged();
178      Evaluator.QualityParameter.ActualNameChanged += QualityParameterOnActualNameChanged;
179    }
180
181    protected virtual void QualityParameterOnActualNameChanged(object sender, EventArgs e) {
182      ParameterizeOperators();
183    }
184
185    protected override void ParameterizeOperators() {
186      base.ParameterizeOperators();
187      Parameterize();
188    }
189
190    private void Parameterize() {
191      foreach (var op in Operators.OfType<ISingleObjectiveEvaluationOperator<TEncodedSolution>>())
192        op.Evaluate = Evaluate;
193      foreach (var op in Operators.OfType<ISingleObjectiveAnalysisOperator<TEncodedSolution>>())
194        op.Analyze = Analyze;
195      foreach (var op in Operators.OfType<INeighborBasedOperator<TEncodedSolution>>())
196        op.GetNeighbors = GetNeighbors;
197      foreach (var op in Operators.OfType<ISolutionSimilarityCalculator>()) {
198        op.SolutionVariableName = Encoding.Name;
199        op.QualityVariableName = Evaluator.QualityParameter.ActualName;
200      }
201    }
202
203    private void RegisterEventHandlers() {
204      BoolValueParameterChangeHandler.Create(MaximizationParameter, OnMaximizationChanged);
205    }
206
207    #region ISingleObjectiveHeuristicOptimizationProblem Members
208    IParameter ISingleObjectiveHeuristicOptimizationProblem.MaximizationParameter {
209      get { return Parameters["Maximization"]; }
210    }
211    IParameter ISingleObjectiveHeuristicOptimizationProblem.BestKnownQualityParameter {
212      get { return Parameters["BestKnownQuality"]; }
213    }
214    ISingleObjectiveEvaluator ISingleObjectiveHeuristicOptimizationProblem.Evaluator {
215      get { return Evaluator; }
216    }
217    #endregion
218
219    public event EventHandler MaximizationChanged;
220    protected void OnMaximizationChanged() {
221      MaximizationChanged?.Invoke(this, EventArgs.Empty);
222    }
223  }
224}
Note: See TracBrowser for help on using the repository browser.