Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Optimization/3.3/BasicProblems/Problem.cs @ 17610

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

#2521: Removed unnecessary default ctors from problem base classes.

File size: 8.3 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("D877082E-9E77-4CB1-ABDB-35F63878E116")]
33  public abstract class Problem<TEncoding, TEncodedSolution, TEvaluator> : EncodedProblem,
34    IHeuristicOptimizationProblem, IProblemDefinition<TEncoding, TEncodedSolution>, IStorableContent
35    where TEncoding : class, IEncoding<TEncodedSolution>
36    where TEncodedSolution : class, IEncodedSolution
37    where TEvaluator : class, IEvaluator {
38
39
40    //TODO remove parameter for encoding?
41    protected IValueParameter<TEncoding> EncodingParameter {
42      get { return (IValueParameter<TEncoding>)Parameters["Encoding"]; }
43    }
44    //mkommend necessary for reuse of operators if the encoding changes
45    private TEncoding oldEncoding;
46    public TEncoding Encoding {
47      get { return EncodingParameter.Value; }
48      protected set {
49        if (value == null) throw new ArgumentNullException("Encoding must not be null.");
50        EncodingParameter.Value = value;
51      }
52    }
53
54    ISolutionCreator IHeuristicOptimizationProblem.SolutionCreator {
55      get { return Encoding.SolutionCreator; }
56    }
57    IParameter IHeuristicOptimizationProblem.SolutionCreatorParameter {
58      get { return Encoding.SolutionCreatorParameter; }
59    }
60    event EventHandler IHeuristicOptimizationProblem.SolutionCreatorChanged {
61      add {
62        if (Encoding != null) Encoding.SolutionCreatorChanged += value;
63      }
64      remove {
65        if (Encoding != null) Encoding.SolutionCreatorChanged -= value;
66      }
67    }
68
69    //TODO is a parameter for the evaluator really necessary, only single-objective or multi-objective evulators calling the func are possible
70    public ValueParameter<TEvaluator> EvaluatorParameter {
71      get { return (ValueParameter<TEvaluator>)Parameters["Evaluator"]; }
72    }
73    public TEvaluator Evaluator {
74      get { return EvaluatorParameter.Value; }
75      protected set { EvaluatorParameter.Value = value; }
76    }
77    IEvaluator IHeuristicOptimizationProblem.Evaluator {
78      get { return Evaluator; }
79    }
80    IParameter IHeuristicOptimizationProblem.EvaluatorParameter {
81      get { return EvaluatorParameter; }
82    }
83
84    public event EventHandler EvaluatorChanged;
85    protected virtual void OnEvaluatorChanged() {
86      EventHandler handler = EvaluatorChanged;
87      if (handler != null)
88        handler(this, EventArgs.Empty);
89    }
90
91
92    protected override IEnumerable<IItem> GetOperators() {
93      if (Encoding == null) return base.GetOperators();
94      return base.GetOperators().Concat(Encoding.Operators);
95    }
96    public override IEnumerable<IParameterizedItem> ExecutionContextItems {
97      get {
98        if (Encoding == null) return base.ExecutionContextItems;
99        return base.ExecutionContextItems.Concat(new[] { Encoding });
100      }
101    }
102
103    protected Problem(TEncoding encoding) : base() {
104      if (encoding == null) throw new ArgumentNullException("encoding");
105      Parameters.Add(new ValueParameter<TEncoding>("Encoding", "Describes the configuration of the encoding, what the variables are called, what type they are and their bounds if any.", encoding) { Hidden = true });
106      Parameters.Add(new ValueParameter<TEvaluator>("Evaluator", "The operator used to evaluate a solution.") { Hidden = true });
107
108      oldEncoding = Encoding;
109      Parameterize();
110
111      RegisterEvents();
112    }
113
114    protected Problem(Problem<TEncoding, TEncodedSolution, TEvaluator> original, Cloner cloner)
115      : base(original, cloner) {
116      oldEncoding = cloner.Clone(original.oldEncoding);
117      RegisterEvents();
118    }
119
120    [StorableConstructor]
121    protected Problem(StorableConstructorFlag _) : base(_) { }
122    [StorableHook(HookType.AfterDeserialization)]
123    private void AfterDeserialization() {
124      oldEncoding = Encoding;
125      RegisterEvents();
126    }
127
128    private void RegisterEvents() {
129      EncodingParameter.ValueChanged += (o, e) => { ParameterizeOperators(); OnEncodingChanged(); };
130      EvaluatorParameter.ValueChanged += (o, e) => { ParameterizeOperators(); OnEvaluatorChanged(); };
131      //var multiEncoding = Encoding as MultiEncoding;
132      //if (multiEncoding != null) multiEncoding.EncodingsChanged += MultiEncodingOnEncodingsChanged;
133    }
134
135    protected override void ParameterizeOperators() {
136      base.ParameterizeOperators();
137      Parameterize();
138    }
139
140    protected virtual void OnEncodingChanged() {
141      OnOperatorsChanged();
142      OnReset();
143    }
144
145    private void Parameterize() {
146      if (oldEncoding != null) {
147        AdaptEncodingOperators(oldEncoding, Encoding);
148        //var oldMultiEncoding = oldEncoding as MultiEncoding;
149        //if (oldMultiEncoding != null)
150        //  oldMultiEncoding.EncodingsChanged -= MultiEncodingOnEncodingsChanged;
151      }
152      oldEncoding = Encoding;
153
154      foreach (var op in Operators.OfType<IEncodingOperator<TEncodedSolution>>())
155        op.EncodingParameter.ActualName = EncodingParameter.Name;
156
157      Encoding.ConfigureOperators(Operators);
158      //var multiEncoding = Encoding as MultiEncoding;
159      //if (multiEncoding != null) multiEncoding.EncodingsChanged += MultiEncodingOnEncodingsChanged;
160    }
161
162    //protected override void OnSolutionCreatorChanged() {
163    //  base.OnSolutionCreatorChanged();
164    //  Encoding.SolutionCreator = SolutionCreator;
165    //}
166
167    private static void AdaptEncodingOperators(IEncoding oldEncoding, IEncoding newEncoding) {
168      if (oldEncoding.GetType() != newEncoding.GetType()) return;
169
170      if (oldEncoding is CombinedEncoding) {
171        var oldMultiEncoding = (CombinedEncoding)oldEncoding;
172        var newMultiEncoding = (CombinedEncoding)newEncoding;
173        if (!oldMultiEncoding.Encodings.SequenceEqual(newMultiEncoding.Encodings, new TypeEqualityComparer<IEncoding>())) return;
174
175        var nestedEncodings = oldMultiEncoding.Encodings.Zip(newMultiEncoding.Encodings, (o, n) => new { oldEnc = o, newEnc = n });
176        foreach (var multi in nestedEncodings)
177          AdaptEncodingOperators(multi.oldEnc, multi.newEnc);
178      }
179
180      var comparer = new TypeEqualityComparer<IOperator>();
181      var cloner = new Cloner();
182      var oldOperators = oldEncoding.Operators;
183      var newOperators = newEncoding.Operators;
184
185      cloner.RegisterClonedObject(oldEncoding, newEncoding);
186      var operators = oldOperators.Intersect(newOperators, comparer)
187                                  .Select(cloner.Clone)
188                                  .Union(newOperators, comparer).ToList();
189
190      newEncoding.ConfigureOperators(operators);
191      newEncoding.Operators = operators;
192    }
193
194    protected override IEnumerable<KeyValuePair<string, IItem>> GetCollectedValues(IValueParameter param) {
195      if (param.Value == null) yield break;
196      if (param.GetsCollected) {
197        if (param == EncodingParameter) // store only the name of the encoding
198          yield return new KeyValuePair<string, IItem>(String.Empty, new StringValue(EncodingParameter.Value.Name));
199        else yield return new KeyValuePair<string, IItem>(String.Empty, param.Value);
200      }
201      var parameterizedItem = param.Value as IParameterizedItem;
202      if (parameterizedItem != null) {
203        var children = new Dictionary<string, IItem>();
204        parameterizedItem.CollectParameterValues(children);
205        foreach (var child in children) yield return child;
206      }
207    }
208  }
209}
Note: See TracBrowser for help on using the repository browser.