Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2522_RefactorPluginInfrastructure/HeuristicLab.Optimization/3.3/BasicProblems/SingleObjectiveBasicProblem.cs

Last change on this file was 15973, checked in by gkronber, 6 years ago

#2522: merged trunk changes from r13402:15972 to branch resolving conflicts where necessary

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