Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ProblemRefactoring/HeuristicLab.Optimization/3.3/BasicProblems/Problem.cs @ 14604

Last change on this file since 14604 was 14429, checked in by abeham, 8 years ago

#2701, #2708: Made a new branch from ProblemRefactoring and removed ScopedBasicAlgorithm branch (which becomes MemPR branch)

File size: 7.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Parameters;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.Optimization {
31  [StorableClass]
32  public abstract class Problem<TEncoding, TSolution, TEvaluator> : Problem,
33    IHeuristicOptimizationProblem, IProblemDefinition<TEncoding, TSolution>, IStorableContent
34    where TEncoding : class, IEncoding<TSolution>
35    where TSolution : class, ISolution
36    where TEvaluator : class, IEvaluator {
37
38    public string Filename { get; set; } // TODO: Really okay here? should be in Problem (non-generic)
39
40    //TODO remove parametr 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 { Encoding.SolutionCreatorChanged += value; }
62      remove { Encoding.SolutionCreatorChanged -= value; }
63    }
64
65    //TODO is a parameter for the evaluator really necessary, only single-objective or multi-objective evulators calling the func are possible
66    public ValueParameter<TEvaluator> EvaluatorParameter {
67      get { return (ValueParameter<TEvaluator>)Parameters["Evaluator"]; }
68    }
69    public TEvaluator Evaluator {
70      get { return EvaluatorParameter.Value; }
71      protected set { EvaluatorParameter.Value = value; }
72    }
73    IEvaluator IHeuristicOptimizationProblem.Evaluator { get { return Evaluator; } }
74    IParameter IHeuristicOptimizationProblem.EvaluatorParameter { get { return EvaluatorParameter; } }
75
76    public event EventHandler EvaluatorChanged;
77    protected virtual void OnEvaluatorChanged() {
78      EventHandler handler = EvaluatorChanged;
79      if (handler != null)
80        handler(this, EventArgs.Empty);
81    }
82
83    // TODO: There is no way to access the Operators collection other than through OperatorParameter.Value
84    protected override IEnumerable<IItem> GetOperators() {
85      if (Encoding == null) return base.GetOperators();
86      return base.GetOperators().Concat(Encoding.Operators);
87    }
88    public override IEnumerable<IParameterizedItem> ExecutionContextItems {
89      get {
90        if (Encoding == null) return base.ExecutionContextItems;
91        return base.ExecutionContextItems.Concat(new[] { Encoding });
92      }
93    }
94
95    protected Problem()
96      : base() {
97      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."));
98      Parameters.Add(new ValueParameter<TEvaluator>("Evaluator", "The operator used to evaluate a solution."));
99
100      if (Encoding != null) {
101        oldEncoding = Encoding;
102        Parameterize();
103      }
104      RegisterEvents();
105    }
106    protected Problem(TEncoding encoding) {
107      if (encoding == null) throw new ArgumentNullException("encoding");
108      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));
109      Parameters.Add(new ValueParameter<TEvaluator>("Evaluator", "The operator used to evaluate a solution."));
110
111      oldEncoding = Encoding;
112      Parameterize();
113
114      RegisterEvents();
115    }
116
117    protected Problem(Problem<TEncoding, TSolution, TEvaluator> original, Cloner cloner)
118      : base(original, cloner) {
119      oldEncoding = cloner.Clone(original.oldEncoding);
120      RegisterEvents();
121    }
122
123    [StorableConstructor]
124    protected Problem(bool deserializing) : base(deserializing) { }
125    [StorableHook(HookType.AfterDeserialization)]
126    private void AfterDeserialization() {
127      oldEncoding = Encoding;
128      RegisterEvents();
129    }
130
131    private void RegisterEvents() {
132      EncodingParameter.ValueChanged += (o, e) => OnEncodingChanged();
133      EvaluatorParameter.ValueChanged += (o, e) => OnEvaluatorChanged();
134      //var multiEncoding = Encoding as MultiEncoding;
135      //if (multiEncoding != null) multiEncoding.EncodingsChanged += MultiEncodingOnEncodingsChanged;
136    }
137
138    protected virtual void OnEncodingChanged() {
139      Parameterize();
140
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<TSolution>>())
155        op.EncodingParameter.ActualName = EncodingParameter.Name;
156
157      //var multiEncoding = Encoding as MultiEncoding;
158      //if (multiEncoding != null) multiEncoding.EncodingsChanged += MultiEncodingOnEncodingsChanged;
159    }
160
161    //protected override void OnSolutionCreatorChanged() {
162    //  base.OnSolutionCreatorChanged();
163    //  Encoding.SolutionCreator = SolutionCreator;
164    //}
165
166    private static void AdaptEncodingOperators(IEncoding oldEncoding, IEncoding newEncoding) {
167      if (oldEncoding.GetType() != newEncoding.GetType()) return;
168
169      if (oldEncoding is CombinedEncoding) {
170        var oldMultiEncoding = (CombinedEncoding)oldEncoding;
171        var newMultiEncoding = (CombinedEncoding)newEncoding;
172        if (!oldMultiEncoding.Encodings.SequenceEqual(newMultiEncoding.Encodings, new TypeEqualityComparer<IEncoding>())) return;
173
174        var nestedEncodings = oldMultiEncoding.Encodings.Zip(newMultiEncoding.Encodings, (o, n) => new { oldEnc = o, newEnc = n });
175        foreach (var multi in nestedEncodings)
176          AdaptEncodingOperators(multi.oldEnc, multi.newEnc);
177      }
178
179      var comparer = new TypeEqualityComparer<IOperator>();
180      var cloner = new Cloner();
181      var oldOperators = oldEncoding.Operators;
182      var newOperators = newEncoding.Operators;
183
184      cloner.RegisterClonedObject(oldEncoding, newEncoding);
185      var operators = oldOperators.Intersect(newOperators, comparer)
186                                  .Select(cloner.Clone)
187                                  .Union(newOperators, comparer).ToList();
188
189      newEncoding.ConfigureOperators(operators);
190      newEncoding.Operators = operators;
191    }
192  }
193}
Note: See TracBrowser for help on using the repository browser.