Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Problems.NK/3.3/NKLandscape.cs @ 17544

Last change on this file since 17544 was 17544, checked in by abeham, 4 years ago

#2521: worked on refactoring, worked a lot on binary encoding / problems

File size: 13.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.Linq;
24using System.Security.Cryptography;
25using System.Threading;
26using HEAL.Attic;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Encodings.BinaryVectorEncoding;
31using HeuristicLab.Optimization;
32using HeuristicLab.Parameters;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Random;
35
36namespace HeuristicLab.Problems.NK {
37  [Item("NK Landscape", "Represents an NK landscape optimization problem.")]
38  [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 215)]
39  [StorableType("04294537-87F2-4A9F-BC14-7D4CA700F326")]
40  public sealed class NKLandscape : BinaryVectorProblem {
41
42    #region Parameters
43    public IValueParameter<BoolMatrix> GeneInteractionsParameter {
44      get { return (IValueParameter<BoolMatrix>)Parameters["GeneInteractions"]; }
45    }
46    public IValueParameter<IntValue> SeedParameter {
47      get { return (IValueParameter<IntValue>)Parameters["ProblemSeed"]; }
48    }
49    public IValueParameter<IntValue> InteractionSeedParameter {
50      get { return (IValueParameter<IntValue>)Parameters["InteractionSeed"]; }
51    }
52    public IValueParameter<IntValue> NrOfInteractionsParameter {
53      get { return (IValueParameter<IntValue>)Parameters["NrOfInteractions"]; }
54    }
55    public IValueParameter<IntValue> NrOfFitnessComponentsParameter {
56      get { return (IValueParameter<IntValue>)Parameters["NrOfFitnessComponents"]; }
57    }
58    public IValueParameter<IntValue> QParameter {
59      get { return (IValueParameter<IntValue>)Parameters["Q"]; }
60    }
61    public IValueParameter<DoubleValue> PParameter {
62      get { return (IValueParameter<DoubleValue>)Parameters["P"]; }
63    }
64    public IValueParameter<DoubleArray> WeightsParameter {
65      get { return (IValueParameter<DoubleArray>)Parameters["Weights"]; }
66    }
67    public IConstrainedValueParameter<IInteractionInitializer> InteractionInitializerParameter {
68      get { return (IConstrainedValueParameter<IInteractionInitializer>)Parameters["InteractionInitializer"]; }
69    }
70    public IConstrainedValueParameter<IWeightsInitializer> WeightsInitializerParameter {
71      get { return (IConstrainedValueParameter<IWeightsInitializer>)Parameters["WeightsInitializer"]; }
72    }
73    #endregion
74
75    #region Properties
76    public IInteractionInitializer InteractionInitializer {
77      get { return InteractionInitializerParameter.Value; }
78    }
79    public BoolMatrix GeneInteractions {
80      get { return GeneInteractionsParameter.Value; }
81    }
82    public DoubleArray Weights {
83      get { return WeightsParameter.Value; }
84    }
85    public IntValue InteractionSeed {
86      get { return InteractionSeedParameter.Value; }
87    }
88    public IntValue NrOfFitnessComponents {
89      get { return NrOfFitnessComponentsParameter.Value; }
90    }
91    public IntValue NrOfInteractions {
92      get { return NrOfInteractionsParameter.Value; }
93    }
94    public IWeightsInitializer WeightsInitializer {
95      get { return WeightsInitializerParameter.Value; }
96    }
97    public int Q {
98      get { return QParameter.Value.Value; }
99    }
100    public double P {
101      get { return PParameter.Value.Value; }
102    }
103    public IntValue Seed {
104      get { return SeedParameter.Value; }
105    }
106    #endregion
107
108    [Storable]
109    private MersenneTwister random;
110
111    [ThreadStatic]
112    private static HashAlgorithm hashAlgorithm;
113
114    [ThreadStatic]
115    private static HashAlgorithm hashAlgorithmP;
116
117    private static HashAlgorithm HashAlgorithm {
118      get {
119        if (hashAlgorithm == null) {
120          hashAlgorithm = HashAlgorithm.Create("MD5");
121        }
122        return hashAlgorithm;
123      }
124    }
125
126    private static HashAlgorithm HashAlgorithmP {
127      get {
128        if (hashAlgorithmP == null) {
129          hashAlgorithmP = HashAlgorithm.Create("SHA1");
130        }
131        return hashAlgorithmP;
132      }
133    }
134
135    [StorableConstructor]
136    private NKLandscape(StorableConstructorFlag _) : base(_) { }
137    private NKLandscape(NKLandscape original, Cloner cloner)
138      : base(original, cloner) {
139      random = (MersenneTwister)original.random.Clone(cloner);
140      RegisterEventHandlers();
141    }
142    public NKLandscape()
143      : base() {
144      Maximization = false;
145      random = new MersenneTwister();
146
147      Parameters.Add(new ValueParameter<BoolMatrix>("GeneInteractions", "Every column gives the participating genes for each fitness component."));
148      Parameters.Add(new ValueParameter<IntValue>("ProblemSeed", "The seed used for the random number generator.", new IntValue(0)));
149      random.Reset(Seed.Value);
150
151      Parameters.Add(new ValueParameter<IntValue>("InteractionSeed", "The seed used for the hash function to generate interaction tables.", new IntValue(random.Next())));
152      Parameters.Add(new ValueParameter<IntValue>("NrOfFitnessComponents", "Number of fitness component functions. (nr of columns in the interaction column)", new IntValue(10)));
153      Parameters.Add(new ValueParameter<IntValue>("NrOfInteractions", "Number of genes interacting with each other. (nr of True values per column in the interaction matrix)", new IntValue(3)));
154      Parameters.Add(new ValueParameter<IntValue>("Q", "Number of allowed fitness values in the (virutal) random table, or zero.", new IntValue(0)));
155      Parameters.Add(new ValueParameter<DoubleValue>("P", "Probability of any entry in the (virtual) random table being zero.", new DoubleValue(0)));
156      Parameters.Add(new ValueParameter<DoubleArray>("Weights", "The weights for the component functions. If shorted, will be repeated.", new DoubleArray(new[] { 1.0 })));
157      Parameters.Add(new ConstrainedValueParameter<IInteractionInitializer>("InteractionInitializer", "Initialize interactions within the component functions."));
158      Parameters.Add(new ConstrainedValueParameter<IWeightsInitializer>("WeightsInitializer", "Operator to initialize the weights distribution."));
159
160      //allow just the standard NK[P,Q] formulations at the moment
161      WeightsParameter.Hidden = true;
162      InteractionInitializerParameter.Hidden = true;
163      WeightsInitializerParameter.Hidden = true;
164      EncodingParameter.Hidden = true;
165
166      InitializeInteractionInitializerParameter();
167      InitializeWeightsInitializerParameter();
168
169      InitializeOperators();
170      InitializeInteractions();
171      RegisterEventHandlers();
172    }
173
174    private void InitializeInteractionInitializerParameter() {
175      foreach (var initializer in ApplicationManager.Manager.GetInstances<IInteractionInitializer>())
176        InteractionInitializerParameter.ValidValues.Add(initializer);
177      InteractionInitializerParameter.Value = InteractionInitializerParameter.ValidValues.First(v => v is RandomInteractionsInitializer);
178    }
179
180    private void InitializeWeightsInitializerParameter() {
181      foreach (var initializer in ApplicationManager.Manager.GetInstances<IWeightsInitializer>())
182        WeightsInitializerParameter.ValidValues.Add(initializer);
183      WeightsInitializerParameter.Value = WeightsInitializerParameter.ValidValues.First(v => v is EqualWeightsInitializer);
184    }
185
186    public override IDeepCloneable Clone(Cloner cloner) {
187      return new NKLandscape(this, cloner);
188    }
189
190    [StorableHook(HookType.AfterDeserialization)]
191    private void AfterDeserialization() {
192      RegisterEventHandlers();
193    }
194
195    private void RegisterEventHandlers() {
196      NrOfInteractionsParameter.ValueChanged += InteractionParameter_ValueChanged;
197      NrOfInteractionsParameter.Value.ValueChanged += InteractionParameter_ValueChanged;
198      NrOfFitnessComponentsParameter.ValueChanged += InteractionParameter_ValueChanged;
199      NrOfFitnessComponentsParameter.Value.ValueChanged += InteractionParameter_ValueChanged;
200      InteractionInitializerParameter.ValueChanged += InteractionParameter_ValueChanged;
201      WeightsInitializerParameter.ValueChanged += WeightsInitializerParameter_ValueChanged;
202      SeedParameter.ValueChanged += SeedParameter_ValueChanged;
203      SeedParameter.Value.ValueChanged += SeedParameter_ValueChanged;
204
205      RegisterInteractionInitializerParameterEvents();
206      RegisterWeightsParameterEvents();
207    }
208
209    private void RegisterWeightsParameterEvents() {
210      foreach (var vv in WeightsInitializerParameter.ValidValues) {
211        foreach (var p in vv.Parameters) {
212          if (p.ActualValue != null && p.ActualValue is IStringConvertibleValue) {
213            var v = (IStringConvertibleValue)p.ActualValue;
214            v.ValueChanged += WeightsInitializerParameter_ValueChanged;
215          }
216        }
217      }
218    }
219
220    private void RegisterInteractionInitializerParameterEvents() {
221      foreach (var vv in InteractionInitializerParameter.ValidValues) {
222        foreach (var p in vv.Parameters) {
223          if (p.ActualValue != null && p.ActualValue is IStringConvertibleValue) {
224            var v = (IStringConvertibleValue)p.ActualValue;
225            v.ValueChanged += InteractionParameter_ValueChanged;
226          } else if (p.ActualValue != null && p is IConstrainedValueParameter<IBinaryVectorComparer>) {
227            ((IConstrainedValueParameter<IBinaryVectorComparer>)p).ValueChanged +=
228              InteractionParameter_ValueChanged;
229          }
230        }
231      }
232    }
233
234    protected override void DimensionOnChanged() {
235      base.DimensionOnChanged();
236      NrOfFitnessComponentsParameter.Value = new IntValue(Dimension);
237    }
238
239    private void SeedParameter_ValueChanged(object sender, EventArgs e) {
240      random.Reset(Seed.Value);
241      InteractionSeed.Value = random.Next();
242      InitializeInteractions();
243    }
244
245    private void WeightsInitializerParameter_ValueChanged(object sender, EventArgs e) {
246      InitializeWeights();
247    }
248
249    private void InteractionParameter_ValueChanged(object sender, EventArgs e) {
250      InitializeInteractions();
251    }
252
253    private void InitializeOperators() {
254      NKBitFlipMoveEvaluator nkEvaluator = new NKBitFlipMoveEvaluator();
255      Encoding.ConfigureOperator(nkEvaluator);
256      Operators.Add(nkEvaluator);
257    }
258
259    private void InitializeInteractions() {
260      if (InteractionInitializer != null)
261        GeneInteractionsParameter.Value = InteractionInitializer.InitializeInterations(
262          Dimension,
263          NrOfFitnessComponents.Value,
264          NrOfInteractions.Value, random);
265    }
266
267    private void InitializeWeights() {
268      if (WeightsInitializerParameter.Value != null)
269        WeightsParameter.Value = new DoubleArray(
270          WeightsInitializer.GetWeights(NrOfFitnessComponents.Value)
271          .ToArray());
272    }
273
274    #region Evaluation function
275    private static long Hash(long x, HashAlgorithm hashAlg) {
276      return BitConverter.ToInt64(hashAlg.ComputeHash(BitConverter.GetBytes(x), 0, 8), 0);
277    }
278
279    public static double F_i(long x, long i, long g_i, long seed, int q, double p) {
280      var hash = new Func<long, long>(y => Hash(y, HashAlgorithm));
281      var fi = Math.Abs((double)hash((x & g_i) ^ hash(g_i ^ hash(i ^ seed)))) / long.MaxValue;
282      if (q > 0) { fi = Math.Round(fi * q) / q; }
283      if (p > 0) {
284        hash = y => Hash(y, HashAlgorithmP);
285        var r = Math.Abs((double)hash((x & g_i) ^ hash(g_i ^ hash(i ^ seed)))) / long.MaxValue;
286        fi = (r <= p) ? 0 : fi;
287      }
288      return fi;
289    }
290
291    private static double F(long x, long[] g, double[] w, long seed, ref double[] f_i, int q, double p) {
292      double value = 0;
293      for (int i = 0; i < g.Length; i++) {
294        f_i[i] = F_i(x, i, g[i], seed, q, p);
295        value += w[i % w.Length] * f_i[i];
296      }
297      return value;
298    }
299
300    public static long Encode(BinaryVector v) {
301      long x = 0;
302      for (int i = 0; i < 64 && i < v.Length; i++) {
303        x |= (v[i] ? (long)1 : (long)0) << i;
304      }
305      return x;
306    }
307
308    public static long[] Encode(BoolMatrix m) {
309      long[] x = new long[m.Columns];
310      for (int c = 0; c < m.Columns; c++) {
311        x[c] = 0;
312        for (int r = 0; r < 64 && r < m.Rows; r++) {
313          x[c] |= (m[r, c] ? (long)1 : (long)0) << r;
314        }
315      }
316      return x;
317    }
318
319    public static double[] Normalize(DoubleArray weights) {
320      double sum = 0;
321      double[] w = new double[weights.Length];
322      foreach (var v in weights) {
323        sum += Math.Abs(v);
324      }
325      for (int i = 0; i < weights.Length; i++) {
326        w[i] = Math.Abs(weights[i]) / sum;
327      }
328      return w;
329    }
330
331    public static double Evaluate(BinaryVector vector, BoolMatrix interactions, DoubleArray weights, int seed, out double[] f_i, int q, double p) {
332      long x = Encode(vector);
333      long[] g = Encode(interactions);
334      double[] w = Normalize(weights);
335      f_i = new double[interactions.Columns];
336      return F(x, g, w, (long)seed, ref f_i, q, p);
337    }
338
339    public override ISingleObjectiveEvaluationResult Evaluate(BinaryVector vector, IRandom random, CancellationToken cancellationToken) {
340      double[] f_i; //useful for debugging
341      double quality = Evaluate(vector, GeneInteractions, Weights, InteractionSeed.Value, out f_i, Q, P);
342      return new SingleObjectiveEvaluationResult(quality);
343    }
344    #endregion
345  }
346}
Note: See TracBrowser for help on using the repository browser.