Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 16773 was 16751, checked in by mkommend, 6 years ago

#2521: Renamed Solution to EncodedSolution.

File size: 7.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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 HEAL.Attic;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Parameters;
30
31namespace HeuristicLab.Optimization {
32  [StorableType("2697320D-0259-44BB-BD71-7EE1B10F664C")]
33  public abstract class SingleObjectiveProblem<TEncoding, TEncodedSolution> :
34    Problem<TEncoding, TEncodedSolution, SingleObjectiveEvaluator<TEncodedSolution>>,
35    ISingleObjectiveProblem<TEncoding, TEncodedSolution>,
36    ISingleObjectiveProblemDefinition<TEncoding, TEncodedSolution>
37    where TEncoding : class, IEncoding<TEncodedSolution>
38    where TEncodedSolution : class, IEncodedSolution {
39
40    protected IValueParameter<DoubleValue> BestKnownQualityParameter {
41      get { return (IValueParameter<DoubleValue>)Parameters["BestKnownQuality"]; }
42    }
43
44    protected IFixedValueParameter<BoolValue> MaximizationParameter {
45      get { return (IFixedValueParameter<BoolValue>)Parameters["Maximization"]; }
46    }
47
48    public double BestKnownQuality {
49      get {
50        if (BestKnownQualityParameter.Value == null) return double.NaN;
51        return BestKnownQualityParameter.Value.Value;
52      }
53      set {
54        if (double.IsNaN(value)) {
55          BestKnownQualityParameter.Value = null;
56          return;
57        }
58        if (BestKnownQualityParameter.Value == null) BestKnownQualityParameter.Value = new DoubleValue(value);
59        else BestKnownQualityParameter.Value.Value = value;
60      }
61    }
62
63    [StorableConstructor]
64    protected SingleObjectiveProblem(StorableConstructorFlag _) : base(_) { }
65
66    protected SingleObjectiveProblem(SingleObjectiveProblem<TEncoding, TEncodedSolution> original, Cloner cloner)
67      : base(original, cloner) {
68      ParameterizeOperators();
69    }
70
71    protected SingleObjectiveProblem()
72      : base() {
73      Parameters.Add(new FixedValueParameter<BoolValue>("Maximization", "Set to false if the problem should be minimized.", (BoolValue)new BoolValue(Maximization).AsReadOnly()) { Hidden = true });
74      Parameters.Add(new OptionalValueParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this problem."));
75
76      Operators.Add(Evaluator);
77      Operators.Add(new SingleObjectiveAnalyzer<TEncodedSolution>());
78      Operators.Add(new SingleObjectiveImprover<TEncodedSolution>());
79      Operators.Add(new SingleObjectiveMoveEvaluator<TEncodedSolution>());
80      Operators.Add(new SingleObjectiveMoveGenerator<TEncodedSolution>());
81      Operators.Add(new SingleObjectiveMoveMaker<TEncodedSolution>());
82
83      ParameterizeOperators();
84    }
85
86    protected SingleObjectiveProblem(TEncoding encoding)
87      : base(encoding) {
88      Parameters.Add(new FixedValueParameter<BoolValue>("Maximization", "Set to false if the problem should be minimized.", (BoolValue)new BoolValue(Maximization).AsReadOnly()) { Hidden = true });
89      Parameters.Add(new OptionalValueParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this problem."));
90
91      Operators.Add(Evaluator);
92      Operators.Add(new SingleObjectiveAnalyzer<TEncodedSolution>());
93      Operators.Add(new SingleObjectiveImprover<TEncodedSolution>());
94      Operators.Add(new SingleObjectiveMoveEvaluator<TEncodedSolution>());
95      Operators.Add(new SingleObjectiveMoveGenerator<TEncodedSolution>());
96      Operators.Add(new SingleObjectiveMoveMaker<TEncodedSolution>());
97
98      ParameterizeOperators();
99    }
100
101    [StorableHook(HookType.AfterDeserialization)]
102    private void AfterDeserialization() {
103      ParameterizeOperators();
104    }
105
106    public abstract bool Maximization { get; }
107    public abstract double Evaluate(TEncodedSolution solution, IRandom random);
108    public virtual void Analyze(TEncodedSolution[] solutions, double[] qualities, ResultCollection results, IRandom random) { }
109    public virtual IEnumerable<TEncodedSolution> GetNeighbors(TEncodedSolution solution, IRandom random) {
110      return Enumerable.Empty<TEncodedSolution>();
111    }
112
113    public virtual bool IsBetter(double quality, double bestQuality) {
114      return (Maximization && quality > bestQuality || !Maximization && quality < bestQuality);
115    }
116
117    protected Tuple<TEncodedSolution, double> GetBestSolution(TEncodedSolution[] solutions, double[] qualities) {
118      return GetBestSolution(solutions, qualities, Maximization);
119    }
120    public static Tuple<TEncodedSolution, double> GetBestSolution(TEncodedSolution[] solutions, double[] qualities, bool maximization) {
121      var zipped = solutions.Zip(qualities, (s, q) => new { Solution = s, Quality = q });
122      var best = (maximization ? zipped.OrderByDescending(z => z.Quality) : zipped.OrderBy(z => z.Quality)).First();
123      return Tuple.Create(best.Solution, best.Quality);
124    }
125
126    protected override void OnOperatorsChanged() {
127      base.OnOperatorsChanged();
128      if (Encoding != null) {
129        PruneMultiObjectiveOperators(Encoding);
130        var combinedEncoding = Encoding as CombinedEncoding;
131        if (combinedEncoding != null) {
132          foreach (var encoding in combinedEncoding.Encodings.ToList()) {
133            PruneMultiObjectiveOperators(encoding);
134          }
135        }
136      }
137    }
138
139    private void PruneMultiObjectiveOperators(IEncoding encoding) {
140      if (encoding.Operators.Any(x => x is IMultiObjectiveOperator && !(x is ISingleObjectiveOperator)))
141        encoding.Operators = encoding.Operators.Where(x => !(x is IMultiObjectiveOperator) || x is ISingleObjectiveOperator).ToList();
142
143      foreach (var multiOp in Encoding.Operators.OfType<IMultiOperator>()) {
144        foreach (var moOp in multiOp.Operators.Where(x => x is IMultiObjectiveOperator).ToList()) {
145          multiOp.RemoveOperator(moOp);
146        }
147      }
148    }
149
150    protected override void OnEvaluatorChanged() {
151      base.OnEvaluatorChanged();
152      ParameterizeOperators();
153    }
154
155    private void ParameterizeOperators() {
156      foreach (var op in Operators.OfType<ISingleObjectiveEvaluationOperator<TEncodedSolution>>())
157        op.EvaluateFunc = Evaluate;
158      foreach (var op in Operators.OfType<ISingleObjectiveAnalysisOperator<TEncodedSolution>>())
159        op.AnalyzeAction = Analyze;
160      foreach (var op in Operators.OfType<INeighborBasedOperator<TEncodedSolution>>())
161        op.GetNeighborsFunc = GetNeighbors;
162    }
163
164    #region ISingleObjectiveHeuristicOptimizationProblem Members
165    IParameter ISingleObjectiveHeuristicOptimizationProblem.MaximizationParameter {
166      get { return Parameters["Maximization"]; }
167    }
168    IParameter ISingleObjectiveHeuristicOptimizationProblem.BestKnownQualityParameter {
169      get { return Parameters["BestKnownQuality"]; }
170    }
171    ISingleObjectiveEvaluator ISingleObjectiveHeuristicOptimizationProblem.Evaluator {
172      get { return Evaluator; }
173    }
174    #endregion
175  }
176}
Note: See TracBrowser for help on using the repository browser.