Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11598 was 11598, checked in by mkommend, 9 years ago

#2174: Added first version of refactored individuals.

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