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

Last change on this file since 16811 was 16811, checked in by abeham, 12 months ago

#2521: Removed usage of default constructor

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