Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1215

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