Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17363 was 17334, checked in by mkommend, 5 years ago

#2521: Moved IStorableContent from generic problem implementation to IProblem.

File size: 8.6 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> : Problem,
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()
104      : base() {
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.") { Hidden = true });
106      Parameters.Add(new ValueParameter<TEvaluator>("Evaluator", "The operator used to evaluate a solution.") { Hidden = true });
107     
108      if (Encoding != null) {
109        oldEncoding = Encoding;
110        Parameterize();
111      }
112      RegisterEvents();
113    }
114    protected Problem(TEncoding encoding) {
115      if (encoding == null) throw new ArgumentNullException("encoding");
116      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 });
117      Parameters.Add(new ValueParameter<TEvaluator>("Evaluator", "The operator used to evaluate a solution.") { Hidden = true });
118
119      oldEncoding = Encoding;
120      Parameterize();
121
122      RegisterEvents();
123    }
124
125    protected Problem(Problem<TEncoding, TEncodedSolution, TEvaluator> original, Cloner cloner)
126      : base(original, cloner) {
127      oldEncoding = cloner.Clone(original.oldEncoding);
128      RegisterEvents();
129    }
130
131    [StorableConstructor]
132    protected Problem(StorableConstructorFlag _) : base(_) { }
133    [StorableHook(HookType.AfterDeserialization)]
134    private void AfterDeserialization() {
135      oldEncoding = Encoding;
136      RegisterEvents();
137    }
138
139    private void RegisterEvents() {
140      EncodingParameter.ValueChanged += (o, e) => OnEncodingChanged();
141      EvaluatorParameter.ValueChanged += (o, e) => OnEvaluatorChanged();
142      //var multiEncoding = Encoding as MultiEncoding;
143      //if (multiEncoding != null) multiEncoding.EncodingsChanged += MultiEncodingOnEncodingsChanged;
144    }
145
146    protected virtual void OnEncodingChanged() {
147      Parameterize();
148
149      OnOperatorsChanged();
150      OnReset();
151    }
152
153    private void Parameterize() {
154      if (oldEncoding != null) {
155        AdaptEncodingOperators(oldEncoding, Encoding);
156        //var oldMultiEncoding = oldEncoding as MultiEncoding;
157        //if (oldMultiEncoding != null)
158        //  oldMultiEncoding.EncodingsChanged -= MultiEncodingOnEncodingsChanged;
159      }
160      oldEncoding = Encoding;
161
162      foreach (var op in Operators.OfType<IEncodingOperator<TEncodedSolution>>())
163        op.EncodingParameter.ActualName = EncodingParameter.Name;
164
165      //var multiEncoding = Encoding as MultiEncoding;
166      //if (multiEncoding != null) multiEncoding.EncodingsChanged += MultiEncodingOnEncodingsChanged;
167    }
168
169    //protected override void OnSolutionCreatorChanged() {
170    //  base.OnSolutionCreatorChanged();
171    //  Encoding.SolutionCreator = SolutionCreator;
172    //}
173
174    private static void AdaptEncodingOperators(IEncoding oldEncoding, IEncoding newEncoding) {
175      if (oldEncoding.GetType() != newEncoding.GetType()) return;
176
177      if (oldEncoding is CombinedEncoding) {
178        var oldMultiEncoding = (CombinedEncoding)oldEncoding;
179        var newMultiEncoding = (CombinedEncoding)newEncoding;
180        if (!oldMultiEncoding.Encodings.SequenceEqual(newMultiEncoding.Encodings, new TypeEqualityComparer<IEncoding>())) return;
181
182        var nestedEncodings = oldMultiEncoding.Encodings.Zip(newMultiEncoding.Encodings, (o, n) => new {oldEnc = o, newEnc = n});
183        foreach (var multi in nestedEncodings)
184          AdaptEncodingOperators(multi.oldEnc, multi.newEnc);
185      }
186
187      var comparer = new TypeEqualityComparer<IOperator>();
188      var cloner = new Cloner();
189      var oldOperators = oldEncoding.Operators;
190      var newOperators = newEncoding.Operators;
191
192      cloner.RegisterClonedObject(oldEncoding, newEncoding);
193      var operators = oldOperators.Intersect(newOperators, comparer)
194                                  .Select(cloner.Clone)
195                                  .Union(newOperators, comparer).ToList();
196
197      newEncoding.ConfigureOperators(operators);
198      newEncoding.Operators = operators;
199    }
200
201    protected override IEnumerable<KeyValuePair<string, IItem>> GetCollectedValues(IValueParameter param) {
202      if (param.Value == null) yield break;
203      if (param.GetsCollected) {
204        if (param == EncodingParameter) // store only the name of the encoding
205          yield return new KeyValuePair<string, IItem>(String.Empty, new StringValue(EncodingParameter.Value.Name));
206        else yield return new KeyValuePair<string, IItem>(String.Empty, param.Value);
207      }
208      var parameterizedItem = param.Value as IParameterizedItem;
209      if (parameterizedItem != null) {
210        var children = new Dictionary<string, IItem>();
211        parameterizedItem.CollectParameterValues(children);
212        foreach (var child in children) yield return child;
213      }
214    }
215  }
216}
Note: See TracBrowser for help on using the repository browser.