Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17690 was 17614, checked in by abeham, 5 years ago

#2521: work in progress (removed solution creator parameter from encoding), OrienteeringProblem and test functions are broken

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