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

Last change on this file since 17270 was 17270, checked in by abeham, 3 years ago

#2521: worked on removing virtual from Maximization for single-objective problems

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