source: branches/ProgrammableProblem/HeuristicLab.Problems.Programmable/3.3/Encodings/IntegerEncoding.cs @ 11588

Last change on this file since 11588 was 11588, checked in by mkommend, 8 years ago

#2174: Adapted encodings to store its specific parameters in the standard parameter collection.

File size: 11.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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.Encodings.IntegerVectorEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.PluginInfrastructure;
33
34namespace HeuristicLab.Problems.Programmable {
35  [Item("IntegerEncoding", "Describes an integer vector encoding.")]
36  [StorableClass]
37  public class IntegerEncoding : Encoding<IIntegerVectorCreator> {
38    #region Encoding Parameters
39    private IFixedValueParameter<IntValue> lengthParameter;
40    public IFixedValueParameter<IntValue> LengthParameter {
41      get { return lengthParameter; }
42      set {
43        if (value == null) throw new ArgumentNullException("Length parameter must not be null.");
44        if (value.Value == null) throw new ArgumentNullException("Length parameter value must not be null.");
45        if (lengthParameter == value) return;
46
47        if (lengthParameter != null) Parameters.Remove(lengthParameter);
48        lengthParameter = value;
49        Parameters.Add(lengthParameter);
50        OnLengthParameterChanged();
51      }
52    }
53
54    private IValueParameter<IntMatrix> boundsParameter;
55    public IValueParameter<IntMatrix> BoundsParameter {
56      get { return boundsParameter; }
57      set {
58        if (value == null) throw new ArgumentNullException("Bounds parameter must not be null.");
59        if (boundsParameter == value) return;
60
61        if (boundsParameter != null) Parameters.Remove(boundsParameter);
62        boundsParameter = value;
63        Parameters.Add(boundsParameter);
64        OnBoundsParameterChanged();
65      }
66    }
67    #endregion
68
69    public int Length {
70      get { return LengthParameter.Value.Value; }
71      set { LengthParameter.Value.Value = value; }
72    }
73    public IntMatrix Bounds {
74      get { return BoundsParameter.Value; }
75      set { BoundsParameter.Value = value; }
76    }
77
78    [StorableConstructor]
79    protected IntegerEncoding(bool deserializing) : base(deserializing) { }
80    [StorableHook(HookType.AfterDeserialization)]
81    private void AfterDeserialization() {
82      RegisterParameterEvents();
83      DiscoverOperators();
84    }
85
86    protected IntegerEncoding(IntegerEncoding original, Cloner cloner)
87      : base(original, cloner) {
88      lengthParameter = cloner.Clone(original.lengthParameter);
89      boundsParameter = cloner.Clone(original.boundsParameter);
90      RegisterParameterEvents();
91    }
92    public override IDeepCloneable Clone(Cloner cloner) { return new IntegerEncoding(this, cloner); }
93
94    public IntegerEncoding(string name, int length, int min, int max, int? step = null)
95      : base(name) {
96      if (min >= max) throw new ArgumentException("min must be less than max", "min");
97      if (step.HasValue && step.Value <= 0) throw new ArgumentException("step must be greater than zero or null", "step");
98
99      var bounds = new IntMatrix(1, step.HasValue ? 3 : 2);
100      bounds[0, 0] = min;
101      bounds[0, 1] = max;
102      if (step.HasValue) bounds[0, 2] = step.Value;
103
104      LengthParameter = new FixedValueParameter<IntValue>(Name + "Length", new IntValue(length));
105      BoundsParameter = new ValueParameter<IntMatrix>(Name + "Bounds", bounds);
106
107      SolutionCreator = new UniformRandomIntegerVectorCreator();
108      RegisterParameterEvents();
109      DiscoverOperators();
110    }
111    public IntegerEncoding(string name, int length, IList<int> min, IList<int> max, IList<int> step = null)
112      : base(name) {
113      if (min.Count == 0) throw new ArgumentException("Bounds must be given for the integer parameters.");
114      if (min.Count != max.Count) throw new ArgumentException("min must be of the same length as max", "min");
115      if (step != null && min.Count != step.Count) throw new ArgumentException("step must be of the same length as min or null", "step");
116      if (min.Zip(max, (mi, ma) => mi >= ma).Any(x => x)) throw new ArgumentException("min must be less than max in each dimension", "min");
117
118      var bounds = new IntMatrix(min.Count, step != null ? 3 : 2);
119      for (int i = 0; i < min.Count; i++) {
120        bounds[i, 0] = min[i];
121        bounds[i, 1] = max[i];
122        if (step != null) bounds[i, 2] = step[i];
123      }
124
125      LengthParameter = new FixedValueParameter<IntValue>(Name + "Length", new IntValue(length));
126      BoundsParameter = new ValueParameter<IntMatrix>(Name + "Bounds", bounds);
127
128      SolutionCreator = new UniformRandomIntegerVectorCreator();
129      RegisterParameterEvents();
130      DiscoverOperators();
131    }
132
133    private void OnLengthParameterChanged() {
134      RegisterLengthParameterEvents();
135      ConfigureOperators(Operators);
136    }
137    private void OnBoundsParameterChanged() {
138      RegisterBoundsParameterEvents();
139      ConfigureOperators(Operators);
140    }
141
142    private void RegisterParameterEvents() {
143      RegisterLengthParameterEvents();
144      RegisterBoundsParameterEvents();
145    }
146    private void RegisterLengthParameterEvents() {
147      LengthParameter.ValueChanged += (o, s) => ConfigureOperators(Operators);
148      LengthParameter.Value.ValueChanged += (o, s) => ConfigureOperators(Operators);
149    }
150    private void RegisterBoundsParameterEvents() {
151      BoundsParameter.ValueChanged += (o, s) => ConfigureOperators(Operators);
152      boundsParameter.Value.ToStringChanged += (o, s) => ConfigureOperators(Operators);
153    }
154
155
156    #region Operator Discovery
157    private static readonly IEnumerable<Type> encodingSpecificOperatorTypes;
158    static IntegerEncoding() {
159      encodingSpecificOperatorTypes = new List<Type>() {
160        typeof (IIntegerVectorOperator),
161        typeof (IIntegerVectorCreator),
162        typeof (IIntegerVectorCrossover),
163        typeof (IIntegerVectorManipulator),
164        typeof (IIntegerVectorStdDevStrategyParameterOperator),
165        typeof (IIntegerVectorMultiNeighborhoodShakingOperator),
166      };
167    }
168    private void DiscoverOperators() {
169      var discoveredTypes = ApplicationManager.Manager.GetTypes(encodingSpecificOperatorTypes, true, false, false);
170      var operators = discoveredTypes.Select(t => (IOperator)Activator.CreateInstance(t));
171      var newOperators = operators.Except(Operators, new TypeEqualityComparer<IOperator>()).ToList();
172
173      ConfigureOperators(newOperators);
174      foreach (var @operator in newOperators)
175        encodingOperators.Add(@operator);
176    }
177    #endregion
178
179    public override void ConfigureOperators(IEnumerable<IOperator> operators) {
180      ConfigureBoundedOperators(Operators.OfType<IBoundedIntegerVectorOperator>());
181      ConfigureCreators(Operators.OfType<IIntegerVectorCreator>());
182      ConfigureCrossovers(Operators.OfType<IIntegerVectorCrossover>());
183      ConfigureManipulators(Operators.OfType<IIntegerVectorManipulator>());
184      ConfigureShakingOperators(Operators.OfType<IIntegerVectorMultiNeighborhoodShakingOperator>());
185      ConfigureStrategyVectorOperator(Operators.OfType<IIntegerVectorStdDevStrategyParameterOperator>());
186    }
187
188    #region Specific Operator Wiring
189    private void ConfigureBoundedOperators(IEnumerable<IBoundedIntegerVectorOperator> boundedOperators) {
190      foreach (var boundedOperator in boundedOperators) {
191        boundedOperator.BoundsParameter.ActualName = BoundsParameter.Name;
192      }
193    }
194
195    private void ConfigureCreators(IEnumerable<IIntegerVectorCreator> creators) {
196      foreach (var creator in creators) {
197        creator.IntegerVectorParameter.ActualName = Name;
198        creator.BoundsParameter.ActualName = BoundsParameter.Name;
199        creator.LengthParameter.ActualName = LengthParameter.Name;
200      }
201    }
202
203    private void ConfigureCrossovers(IEnumerable<IIntegerVectorCrossover> crossovers) {
204      foreach (var crossover in crossovers) {
205        crossover.ChildParameter.ActualName = Name;
206        crossover.ParentsParameter.ActualName = Name;
207      }
208    }
209
210    private void ConfigureManipulators(IEnumerable<IIntegerVectorManipulator> manipulators) {
211      foreach (var manipulator in manipulators) {
212        manipulator.IntegerVectorParameter.ActualName = Name;
213        manipulator.IntegerVectorParameter.Hidden = true;
214        var sm = manipulator as ISelfAdaptiveManipulator;
215        if (sm != null) {
216          var p = sm.StrategyParameterParameter as ILookupParameter;
217          if (p != null) {
218            p.ActualName = Name + "Strategy";
219          }
220        }
221      }
222    }
223
224    private void ConfigureShakingOperators(IEnumerable<IIntegerVectorMultiNeighborhoodShakingOperator> shakingOperators) {
225      foreach (var shakingOperator in shakingOperators) {
226        shakingOperator.IntegerVectorParameter.ActualName = Name;
227      }
228    }
229
230    private void ConfigureStrategyVectorOperator(IEnumerable<IIntegerVectorStdDevStrategyParameterOperator> strategyVectorOperators) {
231      var bounds = new DoubleMatrix(Bounds.Rows, Bounds.Columns);
232      for (var i = 0; i < bounds.Rows; i++) {
233        bounds[i, 1] = (int)Math.Ceiling(0.33 * (Bounds[i, 1] - Bounds[i, 0]));
234        bounds[i, 0] = 0;
235        if (bounds.Columns > 2) bounds[i, 2] = Bounds[i, 2];
236      }
237      foreach (var s in strategyVectorOperators) {
238        var c = s as IIntegerVectorStdDevStrategyParameterCreator;
239        if (c != null) {
240          c.BoundsParameter.Value = (DoubleMatrix)bounds.Clone();
241          c.LengthParameter.ActualName = Name;
242          c.StrategyParameterParameter.ActualName = Name + "Strategy";
243        }
244        var m = s as IIntegerVectorStdDevStrategyParameterManipulator;
245        if (m != null) {
246          m.BoundsParameter.Value = (DoubleMatrix)bounds.Clone();
247          m.StrategyParameterParameter.ActualName = Name + "Strategy";
248        }
249        var mm = s as StdDevStrategyVectorManipulator;
250        if (mm != null) {
251          mm.GeneralLearningRateParameter.Value = new DoubleValue(1.0 / Math.Sqrt(2 * Length));
252          mm.LearningRateParameter.Value = new DoubleValue(1.0 / Math.Sqrt(2 * Math.Sqrt(Length)));
253        }
254        var x = s as IIntegerVectorStdDevStrategyParameterCrossover;
255        if (x != null) {
256          x.ParentsParameter.ActualName = Name + "Strategy";
257          x.StrategyParameterParameter.ActualName = Name + "Strategy";
258        }
259      }
260    }
261    #endregion
262  }
263}
Note: See TracBrowser for help on using the repository browser.