Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.MetaOptimization/HeuristicLab.MetaOptimization.Test/Program.cs @ 5212

Last change on this file since 5212 was 5212, checked in by cneumuel, 13 years ago

#1215

  • added normalization for quality values of individuals
File size: 32.1 KB
Line 
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.IO;
5using System.Linq;
6using System.Text;
7using System.Threading;
8using HeuristicLab.Algorithms.EvolutionStrategy;
9using HeuristicLab.Algorithms.GeneticAlgorithm;
10using HeuristicLab.Common;
11using HeuristicLab.Core;
12using HeuristicLab.Data;
13using HeuristicLab.Optimization;
14using HeuristicLab.PluginInfrastructure;
15using HeuristicLab.Problems.MetaOptimization;
16using HeuristicLab.Problems.TestFunctions;
17using HeuristicLab.Random;
18using HeuristicLab.Selection;
19using HeuristicLab.Parameters;
20using HeuristicLab.Operators;
21using System.Diagnostics;
22using HeuristicLab.Encodings.RealVectorEncoding;
23using HeuristicLab.Hive.ExperimentManager;
24
25namespace HeuristicLab.MetaOptimization.Test {
26  class Program {
27    //private static int metaAlgorithmPopulationSize = 50;
28    //private static int metaAlgorithmMaxGenerations = 30;
29    //private static int metaProblemRepetitions = 5;
30    //private static int baseAlgorithmMaxGenerations = 1000;
31
32    private static int metaAlgorithmPopulationSize = 10;
33    private static int metaAlgorithmMaxGenerations = 20;
34    private static int metaProblemRepetitions = 3;
35    private static int baseAlgorithmMaxGenerations = 10;
36
37    static void Main(string[] args) {
38      //TestTableBuilder();
39      //TestShorten();
40
41      //TestIntSampling();
42      //TestDoubleSampling(); return;
43      //TestTypeDiscovery();
44      //TestOperators();
45      //TestCombinations();
46      //TestCombinations2();
47      //TestCombinations3();
48      //TestEnumeratorCollectionEnumerator();
49      //TestCombinations4();
50      //TestAlgorithmPerformanceIssue();
51
52      GeneticAlgorithm baseLevelAlgorithm = new GeneticAlgorithm();
53
54      MetaOptimizationProblem metaOptimizationProblem = new MetaOptimizationProblem();
55      metaOptimizationProblem.Repetitions = new IntValue(metaProblemRepetitions);
56      GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
57      //GeneticAlgorithm metaLevelAlgorithm = GetParallelMetaGA(metaOptimizationProblem);
58      //GeneticAlgorithm metaLevelAlgorithm = GetHiveParallelMetaGA(metaOptimizationProblem);
59
60      //EvolutionStrategy metaLevelAlgorithm = GetMetaES(metaOptimizationProblem);
61
62      IValueConfiguration algorithmVc = SetupGAAlgorithm(baseLevelAlgorithm, metaOptimizationProblem);
63
64      //TestToString(algorithmVc);
65
66
67      //Console.WriteLine("Press enter to start");
68      //Console.ReadLine();
69      //TestConfiguration(algorithmVc, baseLevelAlgorithm);
70
71      //Console.WriteLine("Press enter to start");
72      //Console.ReadLine();
73      TestOptimization(metaLevelAlgorithm);
74
75      //TestMemoryLeak(metaLevelAlgorithm);
76
77      Console.ReadLine();
78    }
79
80    private static void TestAlgorithmPerformanceIssue() {
81      ContentManager.Initialize(new PersistenceContentManager());
82      Queue<TimeSpan> latestExecutionTimes = new Queue<TimeSpan>();
83      int size = 10;
84
85      GeneticAlgorithm ga = new GeneticAlgorithm();
86      ga.PopulationSize.Value = 3;
87      ga.MaximumGenerations.Value = 1;
88      ga.Engine = new SequentialEngine.SequentialEngine();
89
90      MetaOptimizationProblem metaOptimizationProblem = new MetaOptimizationProblem();
91      metaOptimizationProblem.Repetitions = new IntValue(metaProblemRepetitions);
92      GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
93      ParameterConfigurationTree algorithmVc = SetupGAAlgorithm(ga, metaOptimizationProblem);
94      Stopwatch sw = new Stopwatch();
95
96      for (int i = 0; i < 1000; i++) {
97        sw.Start();
98        GeneticAlgorithm clonedGa = (GeneticAlgorithm)ga.Clone();
99        clonedGa.Name = "CLONED GA";
100        algorithmVc.Parameterize(clonedGa);
101        clonedGa.Prepare(true);
102        var executor = new AlgorithmExecutor(clonedGa);
103        executor.StartSync();
104        sw.Stop();
105        latestExecutionTimes.Enqueue(sw.Elapsed);
106        Console.WriteLine("{0}: {1} ({2})", i, sw.Elapsed, latestExecutionTimes.Count > size ? TimeSpan.FromMilliseconds(latestExecutionTimes.Average(t => t.TotalMilliseconds)).ToString() : "-");
107        if (latestExecutionTimes.Count > size) {
108          latestExecutionTimes.Dequeue();
109        }
110        sw.Reset();
111      }
112    }
113
114    private static void TestTableBuilder() {
115      TableBuilder tb = new TableBuilder("column_1", "col2", "col3");
116      tb.AppendRow("1", "humpi", "0.23124");
117      tb.AppendRow("2", "sf", "0.23124");
118      tb.AppendRow("5", "humpi dampti", "0.224");
119      tb.AppendRow("10", "egon asdf", "0.4");
120      tb.AppendRow("15", "MichaelizcMultiVfds", "0.23124564");
121      Console.WriteLine(tb.ToString());
122    }
123
124    private static void TestToInfoString(IValueConfiguration algorithmVc) {
125      var random = new MersenneTwister();
126      Console.WriteLine(algorithmVc.ParameterInfoString);
127      algorithmVc.Randomize(random);
128      Console.WriteLine(algorithmVc.ParameterInfoString);
129      algorithmVc.Randomize(random);
130      Console.WriteLine(algorithmVc.ParameterInfoString);
131      algorithmVc.Randomize(random);
132    }
133
134    private static void TestCombinations() {
135      Console.WriteLine("IntRange 3-18:3");
136      IntValueRange intRange = new IntValueRange(new IntValue(3), new IntValue(18), new IntValue(3));
137      foreach (var val in intRange.GetCombinations()) {
138        Console.WriteLine(val);
139      }
140
141      Console.WriteLine("DoubleRange 1.0-2.5:0.5");
142      var dblRange = new DoubleValueRange(new DoubleValue(0.7), new DoubleValue(2.8), new DoubleValue(0.5));
143      foreach (var val in dblRange.GetCombinations()) {
144        Console.WriteLine(val);
145      }
146
147      Console.WriteLine("PercentRange 33%-66%:33%");
148      var pctRange = new PercentValueRange(new PercentValue(0.32), new PercentValue(0.98), new PercentValue(0.33));
149      foreach (var val in pctRange.GetCombinations()) {
150        Console.WriteLine(val);
151      }
152    }
153
154    private static void TestCombinations3() {
155      Node root = new Node("root");
156      root.ChildNodes.Add(new Node("root.n1"));
157      root.ChildNodes.Add(new Node("root.n2"));
158      Node n3 = new Node("root.n3");
159      n3.ChildNodes.Add(new Node("root.n3.n1"));
160      n3.ChildNodes.Add(new Node("root.n3.n2"));
161      root.ChildNodes.Add(n3);
162
163      Console.WriteLine(root.ToString());
164      Console.WriteLine("--");
165      int cnt = 0;
166      var enumerator = new NodeEnumerator(root);
167      enumerator.Reset();
168      while (enumerator.MoveNext()) {
169        Console.WriteLine(enumerator.Current.ToString());
170        cnt++;
171      }
172      Console.WriteLine("count: " + cnt);
173    }
174
175    private static void TestEnumeratorCollectionEnumerator() {
176      IEnumerable<int> list1 = new int[] { 1, 2, 3, 4, 5 };
177      IEnumerable<int> list2 = new int[] { 10, 20, 30 };
178      IEnumerable<int> list3 = new int[] { 300, 400, 500 };
179
180      var enumerators = new List<IEnumerator>();
181
182      EnumeratorCollectionEnumerator<int> enu = new EnumeratorCollectionEnumerator<int>();
183      enu.AddEnumerator(list1.GetEnumerator());
184      enu.AddEnumerator(list2.GetEnumerator());
185      enu.AddEnumerator(list3.GetEnumerator());
186      enu.Reset();
187      while (enu.MoveNext()) {
188        Console.WriteLine(enu.Current);
189      }
190    }
191
192    private static void TestCombinations4() {
193      GeneticAlgorithm ga = new GeneticAlgorithm();
194      ga.Problem = new SingleObjectiveTestFunctionProblem();
195      ga.Engine = new SequentialEngine.SequentialEngine();
196
197      ParameterConfigurationTree vc = new ParameterConfigurationTree(ga);
198
199      ConfigurePopulationSize(vc, 20, 100, 20);
200      //ConfigureMutationRate(vc, 0.10, 0.60, 0.10);
201      //ConfigureMutationOperator(vc);
202      ConfigureSelectionOperator(vc, true);
203
204      int count = 0;
205      IEnumerator enumerator = new ParameterCombinationsEnumerator(vc);
206      enumerator.Reset();
207      while (enumerator.MoveNext()) {
208        var current = (IValueConfiguration)enumerator.Current;
209        count++;
210        Console.WriteLine(current.ParameterInfoString);
211      }
212      Console.WriteLine("You are about to create {0} algorithms.", count);
213
214      Experiment experiment = vc.GenerateExperiment(ga);
215      //foreach (var opt in experiment.Optimizers) {
216      //  Console.WriteLine(opt.Name);
217      //}
218
219      experiment.Prepare();
220      experiment.Start();
221
222      while (experiment.ExecutionState != ExecutionState.Stopped) {
223        Thread.Sleep(500);
224      }
225    }
226
227    private static void TestOperators() {
228      IRandom random = new MersenneTwister();
229
230      var doubleRange = new DoubleValueRange(new DoubleValue(0), new DoubleValue(100), new DoubleValue(0.1));
231      using (var sw = new StreamWriter("out-DoubleValue.txt")) {
232        for (int i = 0; i < 10000; i++) {
233          var val = new DoubleValue(90);
234          NormalDoubleValueManipulator.ApplyStatic(random, val, doubleRange);
235
236          sw.WriteLine(val);
237        }
238      }
239
240      var percentRange = new PercentValueRange(new PercentValue(0), new PercentValue(1), new PercentValue(0.001));
241      using (var sw = new StreamWriter("out-PercentValue.txt")) {
242        for (int i = 0; i < 10000; i++) {
243          var val = new PercentValue(0.5);
244          NormalDoubleValueManipulator.ApplyStatic(random, val, percentRange.AsDoubleValueRange());
245          sw.WriteLine(val);
246        }
247      }
248
249      var intRange = new IntValueRange(new IntValue(0), new IntValue(100), new IntValue(1));
250      using (var sw = new StreamWriter("out-IntValue.txt")) {
251        for (int i = 0; i < 10000; i++) {
252          var val = new IntValue(50);
253          UniformIntValueManipulator.ApplyStatic(random, val, intRange);
254          sw.WriteLine(val);
255        }
256      }
257
258      Console.ReadLine();
259    }
260
261    private static void TestTypeDiscovery() {
262      PluginLoader.pluginAssemblies.Any();
263
264      var items = ApplicationManager.Manager.GetInstances(typeof(DoubleArray)).ToArray();
265
266      foreach (var item in items) {
267        Console.WriteLine(item.ToString());
268      }
269    }
270
271    private static void TestMemoryLeak(GeneticAlgorithm metaLevelAlgorithm) {
272      IValueConfiguration algorithmVc = ((MetaOptimizationProblem)metaLevelAlgorithm.Problem).ParameterConfigurationTree;
273
274      Console.WriteLine("Starting Memory Test...");
275      Console.ReadLine();
276
277      var clones = new List<object>();
278      for (int i = 0; i < 1000; i++) {
279        var clone = algorithmVc.Clone();
280        clones.Add(clone);
281      }
282
283      Console.WriteLine("Finished. Now GC...");
284      Console.ReadLine();
285
286      GC.Collect();
287
288      Console.WriteLine("Finished!");
289      Console.ReadLine();
290    }
291
292    private static GeneticAlgorithm GetMetaGA(MetaOptimizationProblem metaOptimizationProblem) {
293      GeneticAlgorithm metaLevelAlgorithm = new GeneticAlgorithm();
294      metaLevelAlgorithm.PopulationSize.Value = metaAlgorithmPopulationSize;
295      metaLevelAlgorithm.MaximumGenerations.Value = metaAlgorithmMaxGenerations;
296
297      metaLevelAlgorithm.Problem = metaOptimizationProblem;
298      metaLevelAlgorithm.Engine = new SequentialEngine.SequentialEngine();
299
300      metaLevelAlgorithm.Mutator = ((OptionalConstrainedValueParameter<IManipulator>)((IAlgorithm)metaLevelAlgorithm).Parameters["Mutator"]).ValidValues.Last();
301
302      metaLevelAlgorithm.MutationProbability.Value = 0.15;
303
304      return metaLevelAlgorithm;
305    }
306
307    private static GeneticAlgorithm GetParallelMetaGA(MetaOptimizationProblem metaOptimizationProblem) {
308      GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
309      metaLevelAlgorithm.Engine = new ParallelEngine.ParallelEngine();
310      return metaLevelAlgorithm;
311    }
312
313    private static GeneticAlgorithm GetHiveParallelMetaGA(MetaOptimizationProblem metaOptimizationProblem) {
314      GeneticAlgorithm metaLevelAlgorithm = GetParallelMetaGA(metaOptimizationProblem);
315      metaLevelAlgorithm.Engine = new HiveEngine.HiveEngine();
316      ServiceLocator.Instance.ClientFacadePool.UserName = "cneumuel";
317      ServiceLocator.Instance.ClientFacadePool.Password = "cneumuel";
318      ServiceLocator.Instance.StreamedClientFacadePool.UserName = "cneumuel";
319      ServiceLocator.Instance.StreamedClientFacadePool.Password = "cneumuel";
320      return metaLevelAlgorithm;
321    }
322
323    private static EvolutionStrategy GetMetaES(MetaOptimizationProblem metaOptimizationProblem) {
324      EvolutionStrategy metaLevelAlgorithm = new EvolutionStrategy();
325      metaLevelAlgorithm.PopulationSize.Value = metaAlgorithmPopulationSize;
326      metaLevelAlgorithm.MaximumGenerations.Value = metaAlgorithmMaxGenerations;
327
328      metaLevelAlgorithm.Problem = metaOptimizationProblem;
329      metaLevelAlgorithm.Engine = new SequentialEngine.SequentialEngine();
330
331      metaLevelAlgorithm.Mutator = ((OptionalConstrainedValueParameter<IManipulator>)((IAlgorithm)metaLevelAlgorithm).Parameters["Mutator"]).ValidValues.Last();
332
333      return metaLevelAlgorithm;
334    }
335
336    private static ParameterConfigurationTree SetupGAAlgorithm(GeneticAlgorithm baseLevelAlgorithm, MetaOptimizationProblem metaOptimizationProblem) {
337      baseLevelAlgorithm.Problem = new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem();
338      baseLevelAlgorithm.MaximumGenerations.Value = baseAlgorithmMaxGenerations;
339
340      metaOptimizationProblem.Algorithm = baseLevelAlgorithm;
341      ParameterConfigurationTree algorithmVc = metaOptimizationProblem.ParameterConfigurationTree;
342
343      metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
344        Evaluator = new GriewankEvaluator(),
345        ProblemSize = new IntValue(5)
346      });
347      metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
348        Evaluator = new GriewankEvaluator(),
349        ProblemSize = new IntValue(50)
350      });
351      metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
352        Evaluator = new GriewankEvaluator(),
353        ProblemSize = new IntValue(500)
354      });
355
356      ConfigurePopulationSize(algorithmVc, 12, 100, 1);
357      ConfigureMutationRate(algorithmVc, 0.0, 1.0, 0.01);
358      //ConfigureMutationOperator(algorithmVc);
359      ConfigureElites(algorithmVc, 0, 10, 1);
360      //ConfigureSelectionOperator(algorithmVc, true);
361      return algorithmVc;
362    }
363
364    private static void TestConfiguration(IValueConfiguration algorithmVc, GeneticAlgorithm baseLevelAlgorithm) {
365      IRandom rand = new FastRandom(0);
366      // set random values
367      for (int i = 0; i < 10; i++) {
368        IValueConfiguration clonedVc = (IValueConfiguration)algorithmVc.Clone();
369        GeneticAlgorithm newAlg = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
370        clonedVc.Randomize(rand);
371        clonedVc.Parameterize(newAlg);
372        Console.WriteLine(string.Format("PopSize: original: {0}, randomized: {1}", baseLevelAlgorithm.PopulationSize, newAlg.PopulationSize));
373        Console.WriteLine(string.Format("MutRate: original: {0}, randomized: {1}", baseLevelAlgorithm.MutationProbability, newAlg.MutationProbability));
374        Console.WriteLine(string.Format("MutOp: original: {0}, randomized: {1}", baseLevelAlgorithm.Mutator, newAlg.Mutator));
375        Console.WriteLine(string.Format("SelOp: original: {0}, randomized: {1}", baseLevelAlgorithm.Selector, newAlg.Selector));
376        //Console.WriteLine(string.Format("GrSi: original: {0}, randomized: {1}", "?", ((TournamentSelector)newAlg.Selector).GroupSizeParameter.Value));
377        Console.WriteLine("---");
378      }
379
380      Console.WriteLine("=======================");
381      algorithmVc.Randomize(rand);
382      algorithmVc.Parameterize(baseLevelAlgorithm);
383      // mutate
384      for (int i = 0; i < 10; i++) {
385        IValueConfiguration clonedVc = (IValueConfiguration)algorithmVc.Clone();
386        GeneticAlgorithm newAlg = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
387        //clonedVc.Mutate(rand);
388
389        //.Apply(rand, clonedVc); todo
390        clonedVc.Parameterize(newAlg);
391        Console.WriteLine(string.Format("PopSize: original: {0}, mutated: {1}", baseLevelAlgorithm.PopulationSize, newAlg.PopulationSize));
392        Console.WriteLine(string.Format("MutRate: original: {0}, mutated: {1}", baseLevelAlgorithm.MutationProbability, newAlg.MutationProbability));
393        Console.WriteLine(string.Format("MutOp: original: {0}, mutated: {1}", baseLevelAlgorithm.Mutator, newAlg.Mutator));
394        Console.WriteLine(string.Format("SelOp: original: {0}, mutated: {1}", baseLevelAlgorithm.Selector, newAlg.Selector));
395        //Console.WriteLine(string.Format("GrSi: original: {0}, mutated: {1}", ((TournamentSelector)baseLevelAlgorithm.Selector).GroupSizeParameter.Value, ((TournamentSelector)newAlg.Selector).GroupSizeParameter.Value));
396        Console.WriteLine("---");
397      }
398
399      Console.WriteLine("=======================");
400      // cross
401      for (int i = 0; i < 10; i++) {
402        IValueConfiguration clonedVc1 = (IValueConfiguration)algorithmVc.Clone();
403        IValueConfiguration clonedVc2 = (IValueConfiguration)algorithmVc.Clone();
404
405        GeneticAlgorithm first = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
406        GeneticAlgorithm second = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
407
408        clonedVc1.Randomize(rand);
409        clonedVc1.Parameterize(first);
410
411        clonedVc2.Randomize(rand);
412        clonedVc2.Parameterize(second);
413
414        var popSizeBefore = first.PopulationSize.Value;
415        var mutRateBefore = first.MutationProbability.Value;
416        var mutOpBefore = first.Mutator;
417        var selOpBefore = first.Selector;
418        //var groupSizeBefore = ((TournamentSelector)first.Selector).GroupSizeParameter.Value.Value;
419
420        //clonedVc1.Cross(clonedVc2, rand); todo
421        clonedVc1.Parameterize(first);
422
423        Console.WriteLine(string.Format("PopSize: first: {0}, second: {1}, crossed: {2}", popSizeBefore, second.PopulationSize, first.PopulationSize));
424        Console.WriteLine(string.Format("MutRate: first: {0}, second: {1}, crossed: {2}", mutRateBefore, second.MutationProbability, first.MutationProbability));
425        Console.WriteLine(string.Format("MutOp: first: {0}, second: {1}, crossed: {2}", mutOpBefore, second.Mutator, first.Mutator));
426        Console.WriteLine(string.Format("SelOp: first: {0}, second: {1}, crossed: {2}", selOpBefore, second.Selector, first.Selector));
427        //Console.WriteLine(string.Format("GrSi: first: {0}, second: {1}, crossed: {2}", groupSizeBefore, ((TournamentSelector)second.Selector).GroupSizeParameter.Value, ((TournamentSelector)first.Selector).GroupSizeParameter.Value));
428        Console.WriteLine("---");
429      }
430      Console.WriteLine("=======================");
431    }
432
433    private static void ConfigureMutationOperator(IValueConfiguration algorithmVc) {
434      var mutationOperator = algorithmVc.ParameterConfigurations.Where(x => x.Name == "Mutator").SingleOrDefault();
435      mutationOperator.Optimize = true;
436
437      // uncheck multiMutator to avoid Michalewicz issue
438      var multiMutator = mutationOperator.ValueConfigurations.Where(x => x.ActualValue.Value != null && x.ActualValue.Value.ItemName.StartsWith("Multi")).SingleOrDefault();
439      if (multiMutator != null) {
440        mutationOperator.ValueConfigurations.SetItemCheckedState(multiMutator, false);
441      }
442    }
443
444    private static void ConfigureSelectionOperator(IValueConfiguration algorithmVc, bool configureTournamenSize) {
445      var selectionOperatorPc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "Selector").SingleOrDefault();
446      selectionOperatorPc.Optimize = true;
447
448      foreach (var vc in selectionOperatorPc.ValueConfigurations) {
449        if (vc.ActualValue.ValueDataType == typeof(TournamentSelector)) {
450          selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
451          if (configureTournamenSize) {
452            vc.Optimize = true;
453            ConfigureTournamentGroupSize(vc);
454          }
455        } else if (vc.ActualValue.ValueDataType == typeof(RandomSelector)) {
456          selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
457        } else {
458          selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
459        }
460      }
461    }
462
463    private static void ConfigureTournamentGroupSize(IValueConfiguration tournamentVc) {
464      var groupSizePc = tournamentVc.ParameterConfigurations.Where(x => x.ParameterName == "GroupSize").SingleOrDefault();
465      groupSizePc.Optimize = true;
466
467      groupSizePc.ValueConfigurations.First().Optimize = true;
468      groupSizePc.ValueConfigurations.First().RangeConstraint.LowerBound = new IntValue(0);
469      groupSizePc.ValueConfigurations.First().RangeConstraint.UpperBound = new IntValue(10);
470      groupSizePc.ValueConfigurations.First().RangeConstraint.StepSize = new IntValue(1);
471    }
472
473    private static void ConfigurePopulationSize(IValueConfiguration algorithmVc, int lower, int upper, int stepsize) {
474      var populationSizePc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "PopulationSize").SingleOrDefault();
475      populationSizePc.Optimize = true;
476      var populationSizeVc = populationSizePc.ValueConfigurations.First();
477      populationSizeVc.Optimize = true;
478      populationSizeVc.RangeConstraint.LowerBound = new IntValue(lower);
479      populationSizeVc.RangeConstraint.UpperBound = new IntValue(upper);
480      populationSizeVc.RangeConstraint.StepSize = new IntValue(stepsize);
481    }
482
483    private static void ConfigureMutationRate(IValueConfiguration algorithmVc, double lower, double upper, double stepsize) {
484      var mutationRatePc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "MutationProbability").SingleOrDefault();
485      mutationRatePc.Optimize = true;
486      var mutationRateVc = mutationRatePc.ValueConfigurations.First();
487      mutationRateVc.Optimize = true;
488      mutationRateVc.RangeConstraint.LowerBound = new PercentValue(lower);
489      mutationRateVc.RangeConstraint.UpperBound = new PercentValue(upper);
490      mutationRateVc.RangeConstraint.StepSize = new PercentValue(stepsize);
491    }
492
493    private static void ConfigureElites(IValueConfiguration algorithmVc, int from, int to, int stepSize) {
494      var elitesPc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "Elites").SingleOrDefault();
495      elitesPc.Optimize = true;
496      var elitesVc = elitesPc.ValueConfigurations.First();
497      elitesVc.Optimize = true;
498      elitesVc.RangeConstraint.LowerBound = new IntValue(from);
499      elitesVc.RangeConstraint.UpperBound = new IntValue(to);
500      elitesVc.RangeConstraint.StepSize = new IntValue(stepSize);
501    }
502
503    private static void TestOptimization(EngineAlgorithm metaLevelAlgorithm) {
504      ContentManager.Initialize(new PersistenceContentManager());
505      string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Results");
506      if (!Directory.Exists(path))
507        Directory.CreateDirectory(path);
508      string id = DateTime.Now.ToString("yyyy.MM.dd - HH;mm;ss,ffff");
509      string resultPath = Path.Combine(path, string.Format("{0} - Result.hl", id));
510      string outputPath = Path.Combine(path, string.Format("{0} - Console.txt", id));
511
512      using (var sw = new StreamWriter(outputPath)) {
513        sw.AutoFlush = true;
514
515        StringBuilder sb1 = new StringBuilder();
516        sb1.AppendFormat("Meta.PopulationSize: {0}\n", metaAlgorithmPopulationSize);
517        sb1.AppendFormat("Meta.MaxGenerations: {0}\n", metaAlgorithmMaxGenerations);
518        sb1.AppendFormat("Meta.Repetitions   : {0}\n", metaProblemRepetitions);
519        sb1.AppendFormat("Meta.MutProb       : {0}\n", ((GeneticAlgorithm)metaLevelAlgorithm).MutationProbability.Value);
520        sb1.AppendFormat("Base.MaxGenerations: {0}\n", baseAlgorithmMaxGenerations);
521        sb1.AppendLine("Problems:");
522        foreach (var prob in ((MetaOptimizationProblem)metaLevelAlgorithm.Problem).Problems) {
523          sb1.Append(prob.Name);
524          var sotf = prob as SingleObjectiveTestFunctionProblem;
525          if (sotf != null) {
526            sb1.AppendFormat(" {0}", sotf.ProblemSize.Value);
527          }
528          sb1.AppendLine();
529        }
530        sw.WriteLine(sb1.ToString());
531        Console.WriteLine(sb1.ToString());
532        metaLevelAlgorithm.Stopped += new EventHandler(metaLevelAlgorithm_Stopped);
533        metaLevelAlgorithm.Paused += new EventHandler(metaLevelAlgorithm_Paused);
534        metaLevelAlgorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(metaLevelAlgorithm_ExceptionOccurred);
535
536        metaLevelAlgorithm.Start();
537        int i = 0;
538        int currentGeneration = -1;
539        do {
540          Thread.Sleep(500);
541          if (metaLevelAlgorithm.Results.ContainsKey("Generations") && ((IntValue)metaLevelAlgorithm.Results["Generations"].Value).Value != currentGeneration) {
542            while (metaLevelAlgorithm.Results.Count < 3) Thread.Sleep(100);
543            StringBuilder sb = new StringBuilder();
544            sb.AppendLine(DateTime.Now.ToLongTimeString());
545            sb.AppendLine("=================================");
546
547            sb.AppendLine(metaLevelAlgorithm.ExecutionState.ToString());
548            var rsClone = (ResultCollection)metaLevelAlgorithm.Results.Clone();
549            foreach (var result in rsClone) {
550              sb.AppendLine(result.ToString());
551              if (result.Name == "Population") {
552                RunCollection rc = (RunCollection)result.Value;
553                var orderedRuns = rc.OrderBy(x => x.Results["AverageQualityNormalized"]);
554
555                TableBuilder tb = new TableBuilder("QNorm", "PoSi", "MutRa", "Eli", "SelOp", "MutOp", "NrSelSubScopes");
556                foreach (IRun run in orderedRuns) {
557                  string selector;
558                  if (run.Parameters["Selector"] is TournamentSelector) {
559                    selector = string.Format("{0} ({1})", run.Parameters["Selector"].ToString(), ((TournamentSelector)run.Parameters["Selector"]).GroupSizeParameter.Value.ToString());
560                  } else {
561                    selector = string.Format("{0}", run.Parameters["Selector"].ToString());
562                  }
563
564                  tb.AppendRow(
565                    ((DoubleValue)run.Results["AverageQualityNormalized"]).Value.ToString("#0.00"),
566                    ((IntValue)run.Parameters["PopulationSize"]).Value.ToString(),
567                    ((DoubleValue)run.Parameters["MutationProbability"]).Value.ToString("0.00"),
568                    ((IntValue)run.Parameters["Elites"]).Value.ToString(),
569                    Shorten(selector, 20),
570                    Shorten(run.Parameters.ContainsKey("Mutator") ? run.Parameters["Mutator"].ToString() : "null", 40),
571                    ((ISelector)run.Parameters["Selector"]).NumberOfSelectedSubScopesParameter.Value.ToString());
572                }
573                sb.AppendLine(tb.ToString());
574              }
575            } // foreach
576            //Console.Clear();
577            Console.WriteLine(sb.ToString());
578            sw.WriteLine(sb.ToString());
579            currentGeneration = ((IntValue)metaLevelAlgorithm.Results["Generations"].Value).Value;
580          } // if
581          //if (i % 30 == 0) GC.Collect();
582          i++;
583        } while (metaLevelAlgorithm.ExecutionState != ExecutionState.Stopped);
584      }
585
586      Console.WriteLine();
587      Console.WriteLine("Storing...");
588
589      ContentManager.Save((IStorableContent)metaLevelAlgorithm, resultPath, true);
590      Console.WriteLine("Finished");
591    }
592
593    private static void metaLevelAlgorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
594      Console.WriteLine("metaLevelAlgorithm_ExceptionOccurred");
595      Console.WriteLine(e.Value.ToString());
596      if (e.Value.InnerException != null) {
597        Console.WriteLine(e.Value.InnerException.ToString());
598      }
599    }
600
601    private static void metaLevelAlgorithm_Paused(object sender, EventArgs e) {
602      Console.WriteLine("metaLevelAlgorithm_Paused");
603    }
604
605    private static void metaLevelAlgorithm_Stopped(object sender, EventArgs e) {
606      Console.WriteLine("metaLevelAlgorithm_Stopped");
607    }
608
609    private static void TestShorten() {
610      int n = 8;
611      Console.WriteLine(Shorten("1", n));
612      Console.WriteLine(Shorten("12", n));
613      Console.WriteLine(Shorten("123", n));
614      Console.WriteLine(Shorten("1234", n));
615      Console.WriteLine(Shorten("12345", n));
616      Console.WriteLine(Shorten("123456", n));
617      Console.WriteLine(Shorten("1234567", n));
618      Console.WriteLine(Shorten("12345678", n));
619      Console.WriteLine(Shorten("123456789", n));
620      Console.WriteLine(Shorten("1234567890", n));
621      Console.WriteLine(Shorten("12345678901", n));
622    }
623
624    private static string Shorten(string s, int n) {
625      string placeholder = "..";
626      if (s.Length <= n) return s;
627      int len = n / 2 - placeholder.Length / 2;
628      string start = s.Substring(0, len);
629      string end = s.Substring(s.Length - len, len);
630      return start + placeholder + end;
631    }
632
633    private static void TestIntSampling() {
634      System.Random rand = new System.Random();
635      int lower = 10;
636      int upper = 20;
637      int stepsize = 1;
638      for (int i = 0; i < 100; i++) {
639        int val;
640        do {
641          val = rand.Next(lower / stepsize, upper / stepsize + 1) * stepsize;
642        } while (val < lower || val > upper);
643        Console.WriteLine(val);
644      }
645    }
646
647    private static void TestDoubleSampling() {
648      System.Random rand = new System.Random();
649      double lower = 2;
650      double upper = 3;
651      double stepsize = 0.6;
652      for (int i = 0; i < 100; i++) {
653        double val;
654        do {
655          val = Math.Round((rand.NextDouble() * (upper - lower) + lower) / stepsize, 0) * stepsize;
656        } while (val < lower || val > upper);
657        Console.WriteLine(val);
658      }
659    }
660
661    private static IEnumerable<IItem> GetValidValues(IValueParameter valueParameter) {
662      return ApplicationManager.Manager.GetInstances(valueParameter.DataType).Select(x => (IItem)x).OrderBy(x => x.ItemName);
663    }
664  }
665
666  public class Node {
667    public string Name { get; set; }
668    public int ActualValue { get; set; }
669    public int[] PossibleValues { get; set; }
670    public List<Node> ChildNodes { get; set; }
671
672    public Node(string name) {
673      this.Name = name;
674      PossibleValues = new int[] { 1, 2, 3 };
675      ChildNodes = new List<Node>();
676    }
677
678    public void Init() {
679      this.ActualValue = PossibleValues.First();
680      foreach (var child in ChildNodes) {
681        child.Init();
682      }
683    }
684
685    public override string ToString() {
686      StringBuilder sb = new StringBuilder();
687      sb.Append(string.Format("{0}:{1}", this.Name, this.ActualValue));
688      if (this.ChildNodes.Count() > 0) {
689        sb.Append(" (");
690        var lst = new List<string>();
691        foreach (Node child in ChildNodes) {
692          lst.Add(child.ToString());
693        }
694        sb.Append(string.Join(", ", lst.ToArray()));
695        sb.Append(")");
696      }
697
698      return sb.ToString();
699    }
700  }
701
702  public class NodeEnumerator : IEnumerator<Node> {
703    private Node node;
704    private List<IEnumerator> enumerators;
705
706    public NodeEnumerator(Node node) {
707      this.node = node;
708      this.enumerators = new List<IEnumerator>();
709    }
710
711    public Node Current {
712      get { return node; }
713    }
714    object IEnumerator.Current {
715      get { return Current; }
716    }
717
718    public void Dispose() { }
719
720    public bool MoveNext() {
721      int i = 0;
722      bool ok = false;
723      while (!ok && i < enumerators.Count) {
724        if (enumerators[i].MoveNext()) {
725          ok = true;
726        } else {
727          i++;
728        }
729      }
730
731      if (ok) {
732        for (int k = i - 1; k >= 0; k--) {
733          enumerators[k].Reset();
734          enumerators[k].MoveNext();
735        }
736      } else {
737        return false;
738      }
739
740      node.ActualValue = (int)enumerators[0].Current;
741      return true;
742    }
743
744    public void Reset() {
745      enumerators.Clear();
746      enumerators.Add(node.PossibleValues.GetEnumerator());
747      enumerators[0].Reset();
748
749      foreach (var child in node.ChildNodes) {
750        var enumerator = new NodeEnumerator(child);
751        enumerator.Reset();
752        enumerator.MoveNext();
753        enumerators.Add(enumerator);
754      }
755    }
756  }
757}
Note: See TracBrowser for help on using the repository browser.