Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1215

  • worked on configurability of SymbolicExpressionGrammar
File size: 51.6 KB
Line 
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Diagnostics;
5using System.IO;
6using System.Linq;
7using System.Reflection;
8using System.Text;
9using System.Threading;
10using System.Threading.Tasks;
11using HeuristicLab.Algorithms.EvolutionStrategy;
12using HeuristicLab.Algorithms.GeneticAlgorithm;
13using HeuristicLab.Common;
14using HeuristicLab.Core;
15using HeuristicLab.Data;
16using HeuristicLab.Encodings.RealVectorEncoding;
17using HeuristicLab.Hive.ExperimentManager;
18using HeuristicLab.Optimization;
19using HeuristicLab.Parameters;
20using HeuristicLab.PluginInfrastructure;
21using HeuristicLab.PluginInfrastructure.Manager;
22using HeuristicLab.Problems.DataAnalysis.Symbolic;
23using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
24using HeuristicLab.Problems.MetaOptimization;
25using HeuristicLab.Problems.TestFunctions;
26using HeuristicLab.Random;
27using HeuristicLab.Selection;
28
29namespace HeuristicLab.MetaOptimization.Test {
30  class Program {
31    static void Main(string[] args) {
32      //PluginLoader.pluginAssemblies.Any();
33      PluginManager pm = new PluginManager(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
34      pm.DiscoverAndCheckPlugins();
35
36      pm.Run(pm.Applications.Where(x => x.Name == "TestApp").SingleOrDefault());
37    }
38  }
39
40  [Plugin("TestPlugin", "1.0.0.0")]
41  [PluginFile("HeuristicLab.MetaOptimization.Test.exe", PluginFileType.Assembly)]
42  public class TestPlugin : PluginBase { }
43
44  [Application("TestApp")]
45  public class TestApp : ApplicationBase {
46    //private static int metaAlgorithmPopulationSize = 50;
47    //private static int metaAlgorithmMaxGenerations = 30;
48    //private static int metaProblemRepetitions = 5;
49    //private static int baseAlgorithmMaxGenerations = 1000;
50
51    private static int metaAlgorithmPopulationSize = 10;
52    private static int metaAlgorithmMaxGenerations = 15;
53    private static int metaProblemRepetitions = 3;
54    private static int baseAlgorithmMaxGenerations = 10;
55    private static double mutationProbability = 0.10;
56
57    public override void Run() {
58      ContentManager.Initialize(new PersistenceContentManager());
59
60      //TestTableBuilder();
61      //TestShorten();
62
63      //TestSimilarities(); return;
64      //TestIntSampling();
65      //TestDoubleSampling(); return;
66      //TestTypeDiscovery();
67      //TestOperators();
68      //TestCombinations();
69      //TestCombinations2();
70      //TestCombinations3();
71      //TestEnumeratorCollectionEnumerator();
72      //TestCombinations4(); return;
73      //TestAlgorithmPerformanceIssue(); return;
74      //TestWaitAny();
75      //TestExecutionTimeUpdateInvervalPerformance();
76      //TestMemoryConsumption();
77      //TestNormalCrossover();
78      //TestItemDictionary();
79
80      //TestSymbolicDataAnalysisGrammar(); return;
81
82      MetaOptimizationProblem metaOptimizationProblem = new MetaOptimizationProblem();
83      metaOptimizationProblem.Repetitions = new IntValue(metaProblemRepetitions);
84      GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
85      //GeneticAlgorithm metaLevelAlgorithm = GetParallelMetaGA(metaOptimizationProblem);
86      //GeneticAlgorithm metaLevelAlgorithm = GetHiveParallelMetaGA(metaOptimizationProblem);
87
88      //EvolutionStrategy metaLevelAlgorithm = GetMetaES(metaOptimizationProblem);
89
90      var algorithmVc = SetupGAAlgorithm(typeof(GeneticAlgorithm), metaOptimizationProblem);
91
92      //TestToString(algorithmVc);
93
94
95      //Console.WriteLine("Press enter to start");
96      //Console.ReadLine();
97      TestConfiguration(algorithmVc, typeof(GeneticAlgorithm), metaOptimizationProblem.Problems.First());
98
99      Console.WriteLine("Press enter to start");
100      Console.ReadLine();
101      TestOptimization(metaLevelAlgorithm);
102
103      //TestMemoryLeak(metaLevelAlgorithm);
104
105      Console.ReadLine();
106    }
107
108    private void TestSymbolicDataAnalysisGrammar() {
109      var random = new MersenneTwister();
110
111      var grammar1 = new TypeCoherentExpressionGrammar();
112      var grammar2 = new TypeCoherentExpressionGrammar();
113
114      grammar2.Symbols.Single(x => x.Name == "Addition").InitialFrequency = 0.5;
115
116      Console.WriteLine("========== Grammar1: ==========");
117      PrintGrammar(grammar1);
118      Console.WriteLine("========== Grammar2: ==========");
119      PrintGrammar(grammar2);
120
121
122      RealVector v1 = GetInitialFrequenciesAsRealVector(grammar1);
123      RealVector v2 = GetInitialFrequenciesAsRealVector(grammar2);
124
125      for (int i = 0; i < 10; i++) {
126        RealVector v3 = DiscreteCrossover.Apply(random, new ItemArray<RealVector>(new List<RealVector> { v1, v2 }));
127
128        var grammar3 = new TypeCoherentExpressionGrammar();
129        SetInitialFrequenciesFromRealVector(grammar3, v3);
130
131        Console.WriteLine("\n========== Crossed: ==========");
132        PrintGrammar(grammar3);
133      }
134
135    }
136
137    private static void PrintGrammar(TypeCoherentExpressionGrammar grammar) {
138      foreach (var symbol in grammar.Symbols) {
139        Console.WriteLine("{0} ({1})", symbol.ToString(), symbol.InitialFrequency);
140      }
141    }
142
143    private static RealVector GetInitialFrequenciesAsRealVector(TypeCoherentExpressionGrammar grammar) {
144      var vector = new RealVector(grammar.Symbols.Count());
145      for (int i = 0; i < grammar.Symbols.Count(); i++) {
146        vector[i] = grammar.Symbols.ElementAt(i).InitialFrequency;
147      }
148      return vector;
149    }
150
151    private static void SetInitialFrequenciesFromRealVector(TypeCoherentExpressionGrammar grammar, RealVector vector) {
152      for (int i = 0; i < grammar.Symbols.Count(); i++) {
153        grammar.Symbols.ElementAt(i).InitialFrequency = vector[i];
154      }
155    }
156
157    private static void TestSimilarities() {
158      Console.WriteLine("\nDoubleRange:");
159      var doubleRange = new DoubleValueRange(new DoubleValue(0), new DoubleValue(10), new DoubleValue(1));
160      var a = new DoubleValue(5.0);
161
162      for (double d = 0; d < 10; d += 0.1) {
163        var similarity = doubleRange.CalculateSimilarity(a, new DoubleValue(d));
164        Console.WriteLine("{0}: {1}", d, similarity);
165      }
166
167      Console.WriteLine("\nPecentRange:");
168      var percentRange = new PercentValueRange(new PercentValue(0), new PercentValue(1), new PercentValue(1));
169      var b = new PercentValue(0.05);
170
171      for (double d = 0; d < 1; d += 0.01) {
172        var similarity = percentRange.CalculateSimilarity(b, new PercentValue(d));
173        Console.WriteLine("{0}: {1}", d, similarity);
174      }
175
176      Console.WriteLine("\nIntRange:");
177      var intRange = new IntValueRange(new IntValue(50), new IntValue(100), new IntValue(1));
178      var c = new IntValue(90);
179
180      for (int i = 0; i < 100; i++) {
181        var similarity = intRange.CalculateSimilarity(c, new IntValue(i));
182        Console.WriteLine("{0}: {1}", i, similarity);
183      }
184
185      Console.WriteLine("\nValueConfigurations:");
186      var vc1 = SetupGAAlgorithm(typeof(GeneticAlgorithm), new MetaOptimizationProblem());
187      vc1.AlgorithmConfiguration.ParameterConfigurations.Single(x => x.Name == "Elites").Optimize = true;
188      vc1.AlgorithmConfiguration.ParameterConfigurations.Single(x => x.Name == "PopulationSize").Optimize = true;
189      vc1.AlgorithmConfiguration.ParameterConfigurations.Single(x => x.Name == "MutationProbability").Optimize = true;
190      vc1.AlgorithmConfiguration.ParameterConfigurations.Single(x => x.Name == "Selector").Optimize = true;
191
192      var vc2 = (ParameterConfigurationTree)vc1.Clone();
193      Console.WriteLine("Assert(1): {0}", vc1.CalculateSimilarity(vc2));
194
195      ((IntValue)vc2.AlgorithmConfiguration.ParameterConfigurations.Single(x => x.Name == "PopulationSize").ValueConfigurations[0].ActualValue.Value).Value = 75;
196      Console.WriteLine("{0}", vc1.CalculateSimilarity(vc2));
197
198      ((PercentValue)vc2.AlgorithmConfiguration.ParameterConfigurations.Single(x => x.Name == "MutationProbability").ValueConfigurations[0].ActualValue.Value).Value = 0.15;
199      Console.WriteLine("{0}", vc1.CalculateSimilarity(vc2));
200
201      ((PercentValue)vc2.AlgorithmConfiguration.ParameterConfigurations.Single(x => x.Name == "MutationProbability").ValueConfigurations[0].ActualValue.Value).Value = 0.25;
202      Console.WriteLine("{0}", vc1.CalculateSimilarity(vc2));
203      ((PercentValue)vc2.AlgorithmConfiguration.ParameterConfigurations.Single(x => x.Name == "MutationProbability").ValueConfigurations[0].ActualValue.Value).Value = 0.35;
204      Console.WriteLine("{0}", vc1.CalculateSimilarity(vc2));
205      ((PercentValue)vc2.AlgorithmConfiguration.ParameterConfigurations.Single(x => x.Name == "MutationProbability").ValueConfigurations[0].ActualValue.Value).Value = 0.45;
206      Console.WriteLine("{0}", vc1.CalculateSimilarity(vc2));
207      ((PercentValue)vc2.AlgorithmConfiguration.ParameterConfigurations.Single(x => x.Name == "MutationProbability").ValueConfigurations[0].ActualValue.Value).Value = 0.55;
208      Console.WriteLine("{0}", vc1.CalculateSimilarity(vc2));
209
210      vc2.AlgorithmConfiguration.ParameterConfigurations.Single(x => x.Name == "Selector").ActualValueConfigurationIndex = 3;
211      Console.WriteLine("{0}", vc1.CalculateSimilarity(vc2));
212
213      var random = new Random.MersenneTwister(0);
214      for (int i = 0; i < 10; i++) {
215        vc2.Randomize(random);
216        Console.WriteLine("Randomized: {0}", vc1.CalculateSimilarity(vc2));
217      }
218    }
219
220    private static void TestItemDictionary() {
221      var dict = new ItemDictionary<StringValue, RunCollection>();
222      dict.Add(new StringValue("a"), new RunCollection());
223      dict.Add(new StringValue("b"), new RunCollection());
224      dict.Add(new StringValue("c"), new RunCollection());
225
226      Console.WriteLine(dict.ContainsKey(new StringValue("a")));
227      Console.WriteLine(dict.Count(x => x.Key.Value == "a"));
228
229    }
230
231    private static void TestNormalCrossover() {
232      var random = new MersenneTwister();
233      double d1 = 0.5;
234      double d2 = 0.6;
235      var doubleRange = new DoubleValueRange(new DoubleValue(0.0), new DoubleValue(1.0), new DoubleValue(0.01));
236
237      using (var sw = new StreamWriter("normalCrossover-DoubleValue.txt")) {
238        for (int i = 0; i < 10000; i++) {
239          sw.WriteLine(NormalDoubleValueCrossover.ApplyStatic(random, new DoubleValue(d1), new DoubleValue(d2), doubleRange));
240        }
241      }
242
243      int i1 = 180;
244      int i2 = 160;
245      var intRange = new IntValueRange(new IntValue(100), new IntValue(200), new IntValue(1));
246
247      using (var sw = new StreamWriter("normalCrossover-IntValue.txt")) {
248        for (int i = 0; i < 10000; i++) {
249          sw.WriteLine(NormalIntValueCrossover.ApplyStatic(random, new IntValue(i1), new IntValue(i2), intRange));
250        }
251      }
252    }
253
254    private static void TestMemoryConsumption() {
255      Queue<TimeSpan> latestExecutionTimes = new Queue<TimeSpan>();
256      GeneticAlgorithm ga = new GeneticAlgorithm();
257      ga.PopulationSize.Value = 3;
258      ga.MaximumGenerations.Value = 1;
259      ga.Engine = new SequentialEngine.SequentialEngine();
260      throw new NotImplementedException("TODO: set ga properties correctly");
261
262      MetaOptimizationProblem metaOptimizationProblem = new MetaOptimizationProblem();
263      metaOptimizationProblem.Repetitions = new IntValue(metaProblemRepetitions);
264      GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
265      ParameterConfigurationTree algorithmVc = SetupGAAlgorithm(typeof(GeneticAlgorithm), metaOptimizationProblem);
266      Stopwatch sw = new Stopwatch();
267
268      var algs = new List<IAlgorithm>();
269      for (int i = 0; i < 10000; i++) {
270        sw.Start();
271        GeneticAlgorithm clonedGa = (GeneticAlgorithm)ga.Clone();
272        clonedGa.Name = "CLONED GA";
273        algorithmVc.Parameterize(clonedGa);
274        algs.Add(clonedGa);
275        sw.Reset();
276        ContentManager.Save((IStorableContent)metaLevelAlgorithm, "alg_" + i + ".hl", true);
277        Console.WriteLine("Cloned alg #{0}", i);
278      }
279    }
280
281    private static void TestExecutionTimeUpdateInvervalPerformance() {
282      TableBuilder tb = new TableBuilder("Tasks", "Interval", "TotalExecutionTime", "AvgExecutionTime", "TimeElapsed", "TotalTimeElapsed", "Speedup", "ExecutionTimeChangedCount", "RealExecutionTimeUpdate(ms)");
283      int tasks = 4;
284      int repetitions = 3;
285
286      // warmup
287      RepeatExecuteParallel(3, 1, 1, tb);
288      tb.AppendRow("--", "--", "--", "--", "--", "--", "--", "--", "--");
289      RepeatExecuteParallel(repetitions, tasks, 1, tb);
290      RepeatExecuteParallel(repetitions, tasks, 2.5, tb);
291      RepeatExecuteParallel(repetitions, tasks, 5, tb);
292      RepeatExecuteParallel(repetitions, tasks, 10, tb);
293      RepeatExecuteParallel(repetitions, tasks, 25, tb);
294      RepeatExecuteParallel(repetitions, tasks, 50, tb);
295      RepeatExecuteParallel(repetitions, tasks, 100, tb);
296      RepeatExecuteParallel(repetitions, tasks, 250, tb);
297      RepeatExecuteParallel(repetitions, tasks, 500, tb);
298      RepeatExecuteParallel(repetitions, tasks, 1000, tb);
299      RepeatExecuteParallel(repetitions, tasks, 2500, tb);
300      RepeatExecuteParallel(repetitions, tasks, 5000, tb);
301
302      using (var sw = new StreamWriter("TestExecutionTimeUpdateInvervalPerformance.txt")) {
303        sw.Write(tb.ToString());
304      }
305    }
306
307    private static GeneticAlgorithm CreateGA() {
308      GeneticAlgorithm ga = new GeneticAlgorithm();
309      ga.Problem = new SingleObjectiveTestFunctionProblem() { ProblemSize = new IntValue(250) };
310      ga.Engine = new SequentialEngine.SequentialEngine();
311      ga.SetSeedRandomly.Value = false;
312      ga.Seed.Value = 0;
313      return ga;
314    }
315
316    private static void RepeatExecuteParallel(int repetitions, int tasks, double executionTimeUpdateIntervalMs, TableBuilder tb) {
317      for (int i = 0; i < repetitions; i++) {
318        ExecuteParallel(tasks, executionTimeUpdateIntervalMs, tb);
319        Console.Clear();
320        Console.WriteLine(tb.ToString());
321      }
322    }
323
324    private static void ExecuteParallel(int taskCount, double executionTimeUpdateIntervalMs, TableBuilder tb) {
325      Task<TimeSpan>[] tasks = new Task<TimeSpan>[taskCount];
326      EngineAlgorithm[] algs = new EngineAlgorithm[taskCount];
327      for (int i = 0; i < taskCount; i++) {
328        GeneticAlgorithm alg = CreateGA();
329        //((Engine)alg.Engine).ExecutionTimeUpdateInterval = TimeSpan.FromMilliseconds(executionTimeUpdateIntervalMs);
330        algs[i] = alg;
331      }
332      Console.WriteLine("Creating algs finished.");
333
334      for (int i = 0; i < taskCount; i++) {
335        tasks[i] = new Task<TimeSpan>((alg) => {
336          Console.WriteLine("Task {0} started.", Task.CurrentId);
337
338          Stopwatch swx = new Stopwatch();
339          swx.Start();
340          ((EngineAlgorithm)alg).ExecutionTimeChanged += new EventHandler(Program_ExecutionTimeChanged);
341          ((EngineAlgorithm)alg).StartSync();
342          ((EngineAlgorithm)alg).ExecutionTimeChanged -= new EventHandler(Program_ExecutionTimeChanged);
343          swx.Stop();
344          Console.WriteLine("Task {0} finished.", Task.CurrentId);
345          return swx.Elapsed;
346        }, algs[i]);
347      }
348      Console.WriteLine("Creating tasks finished.");
349      counter = 0;
350      Stopwatch sw = new Stopwatch();
351      sw.Start();
352      foreach (var task in tasks) task.Start();
353      Task.WaitAll(tasks);
354      sw.Stop();
355
356      if (!algs.All(alg => alg.ExecutionState == ExecutionState.Stopped))
357        throw new Exception("Not all algs stopped properly");
358
359      if (!algs.All(alg => ((DoubleValue)alg.Results["BestQuality"].Value).Value == ((DoubleValue)algs.First().Results["BestQuality"].Value).Value))
360        throw new Exception("Not all algs have the same resutls");
361
362      if (tb != null) {
363        double totalExecutionTimeMilliseconds = algs.Select(x => x.ExecutionTime.TotalMilliseconds).Sum();
364        double totalMilliseconds = tasks.Select(t => t.Result.TotalMilliseconds).Sum();
365        tb.AppendRow(
366          taskCount.ToString(),
367          executionTimeUpdateIntervalMs.ToString(),
368          TimeSpan.FromMilliseconds(totalExecutionTimeMilliseconds).ToString(),
369          TimeSpan.FromMilliseconds(totalExecutionTimeMilliseconds / taskCount).ToString(),
370          sw.Elapsed.ToString(),
371          TimeSpan.FromMilliseconds(totalMilliseconds).ToString(),
372          (totalMilliseconds / sw.ElapsedMilliseconds).ToString("0.00"),
373          counter.ToString(),
374          (totalExecutionTimeMilliseconds / counter).ToString("0.00"));
375      }
376      tasks = null;
377      algs = null;
378      GC.Collect();
379      Console.WriteLine("Test finished.");
380    }
381
382    private static int counter = 0;
383    static void Program_ExecutionTimeChanged(object sender, EventArgs e) {
384      System.Threading.Interlocked.Increment(ref counter);
385    }
386
387    private static void TestWaitAny() {
388      System.Random rand = new System.Random();
389      var tasks = new List<Task<int>>();
390      for (int i = 0; i < 10; i++) {
391        tasks.Add(Task.Factory.StartNew<int>((x) => {
392          int sleep = ((int)x - 10) * -1000;
393          Console.WriteLine("sleeping: {0} ms", sleep);
394          Thread.Sleep(0); // make context switch
395          Thread.Sleep(sleep);
396          return (int)x * (int)x;
397        }, i));
398      }
399
400      // --> WaitAll processes tasks lazy but in order.
401      Task.WaitAll();
402      foreach (var task in tasks) {
403        Console.WriteLine(task.Result);
404      }
405
406      // -> WaitAny processes any finished task first. but the finished task needs to be removed from list in order to process all tasks
407      //for (int i = 0; i < 10; i++) {
408      //  var tasksArray = tasks.ToArray();
409      //  var task = tasksArray[Task.WaitAny(tasksArray)];
410      //  Console.WriteLine(task.Result);
411      //  tasks.Remove(task);
412      //}
413
414      Console.WriteLine("Finished TestWaitAny");
415    }
416
417    private static void TestAlgorithmPerformanceIssue() {
418      Queue<TimeSpan> latestExecutionTimes = new Queue<TimeSpan>();
419      int size = 10;
420      var random = new Random.MersenneTwister(0);
421
422      GeneticAlgorithm ga = new GeneticAlgorithm();
423      ga.PopulationSize.Value = 3;
424      ga.MaximumGenerations.Value = 1;
425      ga.Engine = new SequentialEngine.SequentialEngine();
426      ga.Problem = new SingleObjectiveTestFunctionProblem();
427
428      MetaOptimizationProblem metaOptimizationProblem = new MetaOptimizationProblem();
429      //metaOptimizationProblem.Repetitions = new IntValue(metaProblemRepetitions);
430      GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
431      ParameterConfigurationTree algorithmVc = SetupGAAlgorithm(typeof(GeneticAlgorithm), metaOptimizationProblem);
432      algorithmVc.Randomize(random);
433      Stopwatch sw = new Stopwatch();
434
435      var algs = new Queue<IAlgorithm>(); // keep them in memory
436      // -> BINGO! -> .NET cannot hold more than 16 algorithms with their ThreadLocal<T> objects efficiently,
437      // so if they are kept in memory, runtime at the 17. execution drops significantly
438      // because creating ThreadLocal<T> takes all the runtime.
439      // when the algs are not stored in a list however this effect does not occur.
440
441
442      for (int i = 0; i < 1000; i++) {
443        GeneticAlgorithm clonedGa = (GeneticAlgorithm)ga.Clone();
444        clonedGa.Name = "CLONED GA";
445        //algorithmVc.Randomize(random);
446        //algorithmVc.Parameterize(clonedGa);
447        clonedGa.Prepare(true);
448        sw.Start();
449        algs.Enqueue(clonedGa);
450
451        if (algs.Count > 24)
452          algs.Dequeue();
453        clonedGa.StartSync();
454        sw.Stop();
455        latestExecutionTimes.Enqueue(sw.Elapsed);
456        Console.WriteLine("{0}: {1} ({2})", i, sw.Elapsed, latestExecutionTimes.Count > size ? TimeSpan.FromMilliseconds(latestExecutionTimes.Average(t => t.TotalMilliseconds)).ToString() : "-");
457        if (latestExecutionTimes.Count > size) {
458          latestExecutionTimes.Dequeue();
459        }
460        sw.Reset();
461      }
462    }
463
464    private static void TestTableBuilder() {
465      TableBuilder tb = new TableBuilder("column_1", "col2", "col3");
466      tb.AppendRow("1", "humpi", "0.23124");
467      tb.AppendRow("2", "sf", "0.23124");
468      tb.AppendRow("5", "humpi dampti", "0.224");
469      tb.AppendRow("10", "egon asdf", "0.4");
470      tb.AppendRow("15", "MichaelizcMultiVfds", "0.23124564");
471      Console.WriteLine(tb.ToString());
472    }
473
474    private static void TestToInfoString(IValueConfiguration algorithmVc) {
475      var random = new MersenneTwister();
476      Console.WriteLine(algorithmVc.ParameterInfoString);
477      algorithmVc.Randomize(random);
478      Console.WriteLine(algorithmVc.ParameterInfoString);
479      algorithmVc.Randomize(random);
480      Console.WriteLine(algorithmVc.ParameterInfoString);
481      algorithmVc.Randomize(random);
482    }
483
484    private static void TestCombinations() {
485      Console.WriteLine("IntRange 3-18:3");
486      IntValueRange intRange = new IntValueRange(new IntValue(3), new IntValue(18), new IntValue(3));
487      foreach (var val in intRange.GetCombinations()) {
488        Console.WriteLine(val);
489      }
490
491      Console.WriteLine("DoubleRange 1.0-2.5:0.5");
492      var dblRange = new DoubleValueRange(new DoubleValue(0.7), new DoubleValue(2.8), new DoubleValue(0.5));
493      foreach (var val in dblRange.GetCombinations()) {
494        Console.WriteLine(val);
495      }
496
497      Console.WriteLine("PercentRange 33%-66%:33%");
498      var pctRange = new PercentValueRange(new PercentValue(0.32), new PercentValue(0.98), new PercentValue(0.33));
499      foreach (var val in pctRange.GetCombinations()) {
500        Console.WriteLine(val);
501      }
502    }
503
504    private static void TestCombinations3() {
505      Node root = new Node("root");
506      root.ChildNodes.Add(new Node("root.n1"));
507      root.ChildNodes.Add(new Node("root.n2"));
508      Node n3 = new Node("root.n3");
509      n3.ChildNodes.Add(new Node("root.n3.n1"));
510      n3.ChildNodes.Add(new Node("root.n3.n2"));
511      root.ChildNodes.Add(n3);
512
513      Console.WriteLine(root.ToString());
514      Console.WriteLine("--");
515      int cnt = 0;
516      var enumerator = new NodeEnumerator(root);
517      enumerator.Reset();
518      while (enumerator.MoveNext()) {
519        Console.WriteLine(enumerator.Current.ToString());
520        cnt++;
521      }
522      Console.WriteLine("count: " + cnt);
523    }
524
525    private static void TestEnumeratorCollectionEnumerator() {
526      IEnumerable<int> list1 = new int[] { 1, 2, 3, 4, 5 };
527      IEnumerable<int> list2 = new int[] { 10, 20, 30 };
528      IEnumerable<int> list3 = new int[] { 300, 400, 500 };
529
530      var enumerators = new List<IEnumerator>();
531
532      EnumeratorCollectionEnumerator<int> enu = new EnumeratorCollectionEnumerator<int>();
533      enu.AddEnumerator(list1.GetEnumerator());
534      enu.AddEnumerator(list2.GetEnumerator());
535      enu.AddEnumerator(list3.GetEnumerator());
536      enu.Reset();
537      while (enu.MoveNext()) {
538        Console.WriteLine(enu.Current);
539      }
540    }
541
542    private static void TestCombinations4() {
543      GeneticAlgorithm ga = new GeneticAlgorithm();
544      ga.Problem = new SingleObjectiveTestFunctionProblem();
545      ga.Engine = new SequentialEngine.SequentialEngine();
546
547      ParameterConfigurationTree vc = new ParameterConfigurationTree(ga, new SingleObjectiveTestFunctionProblem());
548
549      ConfigurePopulationSize(vc, 20, 100, 20);
550      //ConfigureMutationRate(vc, 0.10, 0.60, 0.10);
551      ConfigureMutationOperator(vc);
552      //ConfigureSelectionOperator(vc, true);
553
554      int count = 0;
555      IEnumerator enumerator = new ParameterCombinationsEnumerator(vc);
556      enumerator.Reset();
557      while (enumerator.MoveNext()) {
558        var current = (IValueConfiguration)enumerator.Current;
559        count++;
560        Console.WriteLine(current.ParameterInfoString);
561      }
562      Console.WriteLine("You are about to create {0} algorithms.", count);
563
564      Experiment experiment = vc.GenerateExperiment(ga);
565      //foreach (var opt in experiment.Optimizers) {
566      //  Console.WriteLine(opt.Name);
567      //}
568
569      experiment.Prepare();
570      experiment.Start();
571
572      while (experiment.ExecutionState != ExecutionState.Stopped) {
573        Thread.Sleep(500);
574      }
575    }
576
577    private static void TestOperators() {
578      IRandom random = new MersenneTwister();
579
580      var doubleRange = new DoubleValueRange(new DoubleValue(0), new DoubleValue(100), new DoubleValue(0.1));
581      using (var sw = new StreamWriter("out-DoubleValue.txt")) {
582        for (int i = 0; i < 10000; i++) {
583          var val = new DoubleValue(90);
584          NormalDoubleValueManipulator.ApplyStatic(random, val, doubleRange);
585
586          sw.WriteLine(val);
587        }
588      }
589
590      var percentRange = new PercentValueRange(new PercentValue(0), new PercentValue(1), new PercentValue(0.001));
591      using (var sw = new StreamWriter("out-PercentValue.txt")) {
592        for (int i = 0; i < 10000; i++) {
593          var val = new PercentValue(0.5);
594          NormalDoubleValueManipulator.ApplyStatic(random, val, percentRange.AsDoubleValueRange());
595          sw.WriteLine(val);
596        }
597      }
598
599      var intRange = new IntValueRange(new IntValue(0), new IntValue(100), new IntValue(1));
600      using (var sw = new StreamWriter("out-IntValue.txt")) {
601        for (int i = 0; i < 10000; i++) {
602          var val = new IntValue(50);
603          UniformIntValueManipulator.ApplyStatic(random, val, intRange);
604          sw.WriteLine(val);
605        }
606      }
607
608      Console.ReadLine();
609    }
610
611    private static void TestTypeDiscovery() {
612      PluginLoader.pluginAssemblies.Any();
613
614      var items = ApplicationManager.Manager.GetInstances(typeof(DoubleArray)).ToArray();
615
616      foreach (var item in items) {
617        Console.WriteLine(item.ToString());
618      }
619    }
620
621    private static void TestMemoryLeak(GeneticAlgorithm metaLevelAlgorithm) {
622      IValueConfiguration algorithmVc = ((MetaOptimizationProblem)metaLevelAlgorithm.Problem).ParameterConfigurationTree;
623
624      Console.WriteLine("Starting Memory Test...");
625      Console.ReadLine();
626
627      var clones = new List<object>();
628      for (int i = 0; i < 1000; i++) {
629        var clone = algorithmVc.Clone();
630        clones.Add(clone);
631      }
632
633      Console.WriteLine("Finished. Now GC...");
634      Console.ReadLine();
635
636      GC.Collect();
637
638      Console.WriteLine("Finished!");
639      Console.ReadLine();
640    }
641
642    private static GeneticAlgorithm GetMetaGA(MetaOptimizationProblem metaOptimizationProblem) {
643      GeneticAlgorithm metaLevelAlgorithm = new GeneticAlgorithm();
644      metaLevelAlgorithm.PopulationSize.Value = metaAlgorithmPopulationSize;
645      metaLevelAlgorithm.MaximumGenerations.Value = metaAlgorithmMaxGenerations;
646
647      metaLevelAlgorithm.Problem = metaOptimizationProblem;
648      metaLevelAlgorithm.Engine = new SequentialEngine.SequentialEngine();
649
650      metaLevelAlgorithm.Mutator = ((OptionalConstrainedValueParameter<IManipulator>)((IAlgorithm)metaLevelAlgorithm).Parameters["Mutator"]).ValidValues.Where(x => x.GetType() == typeof(ParameterConfigurationOnePositionsManipulator)).Single();
651      //metaLevelAlgorithm.Mutator = ((OptionalConstrainedValueParameter<IManipulator>)((IAlgorithm)metaLevelAlgorithm).Parameters["Mutator"]).ValidValues.Where(x => x.GetType() == typeof(ParameterConfigurationAllPositionsManipulator)).Single();
652
653      metaLevelAlgorithm.MutationProbability.Value = mutationProbability;
654      //metaLevelAlgorithm.Selector = ((OptionalConstrainedValueParameter<ISelector>)((IAlgorithm)metaLevelAlgorithm).Parameters["Selector"]).ValidValues.Where(x => x.GetType() == typeof(LinearRankSelector)).Single();
655      //metaLevelAlgorithm.Selector = ((OptionalConstrainedValueParameter<ISelector>)((IAlgorithm)metaLevelAlgorithm).Parameters["Selector"]).ValidValues.Where(x => x.GetType() == typeof(TournamentSelector)).Single();
656      //metaLevelAlgorithm.Selector = ((OptionalConstrainedValueParameter<ISelector>)((IAlgorithm)metaLevelAlgorithm).Parameters["Selector"]).ValidValues.Where(x => x.GetType() == typeof(GenderSpecificSelector)).Single();
657      //metaLevelAlgorithm.Selector = ((OptionalConstrainedValueParameter<ISelector>)((IAlgorithm)metaLevelAlgorithm).Parameters["Selector"]).ValidValues.Where(x => x.GetType() == typeof(BestSelector)).Single();
658      metaLevelAlgorithm.Selector = ((OptionalConstrainedValueParameter<ISelector>)((IAlgorithm)metaLevelAlgorithm).Parameters["Selector"]).ValidValues.Where(x => x.GetType() == typeof(ProportionalSelector)).Single();
659
660      return metaLevelAlgorithm;
661    }
662
663    private static GeneticAlgorithm GetParallelMetaGA(MetaOptimizationProblem metaOptimizationProblem) {
664      GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
665      metaLevelAlgorithm.Engine = new ParallelEngine.ParallelEngine();
666      return metaLevelAlgorithm;
667    }
668
669    private static GeneticAlgorithm GetHiveParallelMetaGA(MetaOptimizationProblem metaOptimizationProblem) {
670      GeneticAlgorithm metaLevelAlgorithm = GetParallelMetaGA(metaOptimizationProblem);
671      metaLevelAlgorithm.Engine = new HiveEngine.HiveEngine();
672      ServiceLocator.Instance.ClientFacadePool.UserName = "cneumuel";
673      ServiceLocator.Instance.ClientFacadePool.Password = "cneumuel";
674      ServiceLocator.Instance.StreamedClientFacadePool.UserName = "cneumuel";
675      ServiceLocator.Instance.StreamedClientFacadePool.Password = "cneumuel";
676      return metaLevelAlgorithm;
677    }
678
679    private static EvolutionStrategy GetMetaES(MetaOptimizationProblem metaOptimizationProblem) {
680      EvolutionStrategy metaLevelAlgorithm = new EvolutionStrategy();
681      metaLevelAlgorithm.PopulationSize.Value = metaAlgorithmPopulationSize;
682      metaLevelAlgorithm.MaximumGenerations.Value = metaAlgorithmMaxGenerations;
683
684      metaLevelAlgorithm.Problem = metaOptimizationProblem;
685      metaLevelAlgorithm.Engine = new SequentialEngine.SequentialEngine();
686
687      metaLevelAlgorithm.Mutator = ((OptionalConstrainedValueParameter<IManipulator>)((IAlgorithm)metaLevelAlgorithm).Parameters["Mutator"]).ValidValues.Last();
688
689      return metaLevelAlgorithm;
690    }
691
692    private static ParameterConfigurationTree SetupGAAlgorithm(Type baseLevelAlgorithmType, MetaOptimizationProblem metaOptimizationProblem) {
693      metaOptimizationProblem.AlgorithmType.Value = baseLevelAlgorithmType;
694      //metaOptimizationProblem.Problems.Clear();
695
696      //metaOptimizationProblem.ProblemType.Value = typeof(SingleObjectiveTestFunctionProblem);
697      //metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
698      //  Evaluator = new GriewankEvaluator(),
699      //  ProblemSize = new IntValue(2)
700      //});
701      //metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
702      //  Evaluator = new GriewankEvaluator(),
703      //  ProblemSize = new IntValue(20)
704      //});
705      //metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
706      //  Evaluator = new GriewankEvaluator(),
707      //  ProblemSize = new IntValue(500)
708      //});
709
710      metaOptimizationProblem.ProblemType.Value = typeof(SymbolicRegressionSingleObjectiveProblem);
711     
712      ParameterConfigurationTree algorithmVc = metaOptimizationProblem.ParameterConfigurationTree;
713      ((IntValue)algorithmVc.AlgorithmConfiguration.ParameterConfigurations.Single(x => x.Name == "MaximumGenerations").ActualValue.Value).Value = baseAlgorithmMaxGenerations;
714
715      //ConfigurePopulationSize(algorithmVc, 15, 20, 1);
716      ConfigureMutationRate(algorithmVc, 0.0, 1.0, 0.01);
717      ConfigureMutationOperator(algorithmVc);
718      //ConfigureElites(algorithmVc, 0, 8, 1);
719      //ConfigureSelectionOperator(algorithmVc, true);
720
721      ConfigureSymbolicExpressionGrammar(algorithmVc);
722
723      return algorithmVc;
724    }
725
726    private static void ConfigureSymbolicExpressionGrammar(ParameterConfigurationTree vc) {
727      var pc = vc.ProblemConfiguration.ParameterConfigurations.Single(x => x.Name == "SymbolicExpressionTreeGrammar");
728      pc.Optimize = true;
729
730      SymbolicExpressionGrammarValueConfiguration symbolicExpressionGrammarVc = null;
731      foreach (var valconf in pc.ValueConfigurations) {
732        if (valconf.ActualValue.Value.ItemName != "TypeCoherentExpressionGrammar") {
733          pc.ValueConfigurations.SetItemCheckedState(valconf, false);
734        } else {
735          symbolicExpressionGrammarVc = valconf as SymbolicExpressionGrammarValueConfiguration;
736        }
737      }
738      symbolicExpressionGrammarVc.Optimize = true;
739
740      var additionPc = symbolicExpressionGrammarVc.ParameterConfigurations.Single(x => x.Name == "Addition");
741      additionPc.Optimize = true;
742      var initialFrequencyVc = ((ParameterizedValueConfiguration)additionPc.ValueConfigurations.First()).ParameterConfigurations.Single(x => x.Name == "InitialFrequency");
743      initialFrequencyVc.Optimize = true;
744    }
745
746    private static void TestConfiguration(ParameterConfigurationTree algorithmVc, Type baseLevelAlgorithmType, IProblem problem) {
747      IRandom rand = new FastRandom(0);
748      var baseLevelAlgorithm = (GeneticAlgorithm)MetaOptimizationUtil.CreateParameterizedAlgorithmInstance(algorithmVc, baseLevelAlgorithmType, problem);
749
750      // set random values
751      for (int i = 0; i < 10; i++) {
752        var clonedVc = (ParameterConfigurationTree)algorithmVc.Clone();
753        GeneticAlgorithm newAlg = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
754        clonedVc.Randomize(rand);
755        clonedVc.Parameterize(newAlg);
756        Console.WriteLine(string.Format("PopSize: original: {0}, randomized: {1}", baseLevelAlgorithm.PopulationSize, newAlg.PopulationSize));
757        Console.WriteLine(string.Format("MutRate: original: {0}, randomized: {1}", baseLevelAlgorithm.MutationProbability, newAlg.MutationProbability));
758        Console.WriteLine(string.Format("MutOp: original: {0}, randomized: {1}", baseLevelAlgorithm.Mutator, newAlg.Mutator));
759        Console.WriteLine(string.Format("SelOp: original: {0}, randomized: {1}", baseLevelAlgorithm.Selector, newAlg.Selector));
760        //Console.WriteLine(string.Format("GrSi: original: {0}, randomized: {1}", "?", ((TournamentSelector)newAlg.Selector).GroupSizeParameter.Value));
761        Console.WriteLine("---");
762      }
763
764      Console.WriteLine("=======================");
765      algorithmVc.Randomize(rand);
766      algorithmVc.Parameterize(baseLevelAlgorithm);
767      // mutate
768      for (int i = 0; i < 10; i++) {
769        var clonedVc = (ParameterConfigurationTree)algorithmVc.Clone();
770        GeneticAlgorithm newAlg = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
771        ParameterConfigurationManipulator.Apply(rand, clonedVc, new UniformIntValueManipulator(), new NormalDoubleValueManipulator());
772        clonedVc.Parameterize(newAlg);
773
774        Console.WriteLine(string.Format("PopSize: original: {0}, mutated: {1}", baseLevelAlgorithm.PopulationSize, newAlg.PopulationSize));
775        Console.WriteLine(string.Format("MutRate: original: {0}, mutated: {1}", baseLevelAlgorithm.MutationProbability, newAlg.MutationProbability));
776        Console.WriteLine(string.Format("MutOp: original: {0}, mutated: {1}", baseLevelAlgorithm.Mutator, newAlg.Mutator));
777        Console.WriteLine(string.Format("SelOp: original: {0}, mutated: {1}", baseLevelAlgorithm.Selector, newAlg.Selector));
778        //Console.WriteLine(string.Format("GrSi: original: {0}, mutated: {1}", ((TournamentSelector)baseLevelAlgorithm.Selector).GroupSizeParameter.Value, ((TournamentSelector)newAlg.Selector).GroupSizeParameter.Value));
779        Console.WriteLine("---");
780      }
781
782      Console.WriteLine("=======================");
783      // cross
784      for (int i = 0; i < 10; i++) {
785        var clonedVc1 = (ParameterConfigurationTree)algorithmVc.Clone();
786        var clonedVc2 = (ParameterConfigurationTree)algorithmVc.Clone();
787
788        GeneticAlgorithm first = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
789        GeneticAlgorithm second = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
790
791        clonedVc1.Randomize(rand);
792        clonedVc1.Parameterize(first);
793
794        clonedVc2.Randomize(rand);
795        clonedVc2.Parameterize(second);
796
797        var popSizeBefore = first.PopulationSize.Value;
798        var mutRateBefore = first.MutationProbability.Value;
799        var mutOpBefore = first.Mutator;
800        var selOpBefore = first.Selector;
801        //var groupSizeBefore = ((TournamentSelector)first.Selector).GroupSizeParameter.Value.Value;
802
803        //clonedVc1.Cross(clonedVc2, rand); todo
804
805        ParameterConfigurationCrossover.Apply(rand, clonedVc1, clonedVc2, new DiscreteIntValueCrossover(), new AverageDoubleValueCrossover());
806        clonedVc1.Parameterize(first);
807
808        Console.WriteLine(string.Format("PopSize: first: {0}, second: {1}, crossed: {2}", popSizeBefore, second.PopulationSize, first.PopulationSize));
809        Console.WriteLine(string.Format("MutRate: first: {0}, second: {1}, crossed: {2}", mutRateBefore, second.MutationProbability, first.MutationProbability));
810        Console.WriteLine(string.Format("MutOp: first: {0}, second: {1}, crossed: {2}", mutOpBefore, second.Mutator, first.Mutator));
811        Console.WriteLine(string.Format("SelOp: first: {0}, second: {1}, crossed: {2}", selOpBefore, second.Selector, first.Selector));
812        //Console.WriteLine(string.Format("GrSi: first: {0}, second: {1}, crossed: {2}", groupSizeBefore, ((TournamentSelector)second.Selector).GroupSizeParameter.Value, ((TournamentSelector)first.Selector).GroupSizeParameter.Value));
813        Console.WriteLine("---");
814      }
815      Console.WriteLine("=======================");
816    }
817
818    private static void ConfigureMutationOperator(ParameterConfigurationTree algorithmVc) {
819      var mutationOperator = algorithmVc.AlgorithmConfiguration.ParameterConfigurations.Where(x => x.Name == "Mutator").SingleOrDefault();
820      mutationOperator.Optimize = true;
821
822      // uncheck multiMutator to avoid Michalewicz issue
823      //var multiMutator = mutationOperator.ValueConfigurations.Where(x => x.ActualValue.Value != null && x.ActualValue.Value.ItemName.StartsWith("Multi")).SingleOrDefault();
824      //if (multiMutator != null) {
825      //  mutationOperator.ValueConfigurations.SetItemCheckedState(multiMutator, false);
826      //}
827
828      // add another normal - don't do this with 'new', because ActualNames will not be set correctly. It should be copied from an existing one
829      // mutationOperator.ValueConfigurations.Add(new ParameterizedValueConfiguration(new NormalAllPositionsManipulator(), typeof(NormalAllPositionsManipulator)), true);
830    }
831
832    private static void ConfigureSelectionOperator(ParameterConfigurationTree algorithmVc, bool configureTournamenSize) {
833      var selectionOperatorPc = algorithmVc.AlgorithmConfiguration.ParameterConfigurations.Where(x => x.Name == "Selector").SingleOrDefault();
834      selectionOperatorPc.Optimize = true;
835
836      foreach (var vc in selectionOperatorPc.ValueConfigurations) {
837        if (vc.ActualValue.ValueDataType == typeof(TournamentSelector)) {
838          selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
839          if (configureTournamenSize) {
840            vc.Optimize = true;
841            ConfigureTournamentGroupSize((ParameterizedValueConfiguration)vc);
842          }
843        } else if (vc.ActualValue.ValueDataType == typeof(RandomSelector)) {
844          selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
845        } else {
846          selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
847        }
848      }
849    }
850
851    private static void ConfigureTournamentGroupSize(ParameterizedValueConfiguration tournamentVc) {
852      var groupSizePc = tournamentVc.ParameterConfigurations.Where(x => x.ParameterName == "GroupSize").SingleOrDefault();
853      groupSizePc.Optimize = true;
854      var groupSizeVc = (RangeValueConfiguration)groupSizePc.ValueConfigurations.First();
855      groupSizeVc.Optimize = true;
856      groupSizeVc.RangeConstraint.LowerBound = new IntValue(0);
857      groupSizeVc.RangeConstraint.UpperBound = new IntValue(10);
858      groupSizeVc.RangeConstraint.StepSize = new IntValue(1);
859    }
860
861    private static void ConfigurePopulationSize(ParameterConfigurationTree algorithmVc, int lower, int upper, int stepsize) {
862      var populationSizePc = algorithmVc.AlgorithmConfiguration.ParameterConfigurations.Where(x => x.Name == "PopulationSize").SingleOrDefault();
863      populationSizePc.Optimize = true;
864      var populationSizeVc = (RangeValueConfiguration)populationSizePc.ValueConfigurations.First();
865      populationSizeVc.Optimize = true;
866      populationSizeVc.RangeConstraint.LowerBound = new IntValue(lower);
867      populationSizeVc.RangeConstraint.UpperBound = new IntValue(upper);
868      populationSizeVc.RangeConstraint.StepSize = new IntValue(stepsize);
869    }
870
871    private static void ConfigureMutationRate(ParameterConfigurationTree algorithmVc, double lower, double upper, double stepsize) {
872      var mutationRatePc = algorithmVc.AlgorithmConfiguration.ParameterConfigurations.Where(x => x.Name == "MutationProbability").SingleOrDefault();
873      mutationRatePc.Optimize = true;
874      var mutationRateVc = (RangeValueConfiguration)mutationRatePc.ValueConfigurations.First();
875      mutationRateVc.Optimize = true;
876      mutationRateVc.RangeConstraint.LowerBound = new PercentValue(lower);
877      mutationRateVc.RangeConstraint.UpperBound = new PercentValue(upper);
878      mutationRateVc.RangeConstraint.StepSize = new PercentValue(stepsize);
879    }
880
881    private static void ConfigureElites(ParameterConfigurationTree algorithmVc, int from, int to, int stepSize) {
882      var elitesPc = algorithmVc.AlgorithmConfiguration.ParameterConfigurations.Where(x => x.Name == "Elites").SingleOrDefault();
883      elitesPc.Optimize = true;
884      var elitesVc = (RangeValueConfiguration)elitesPc.ValueConfigurations.First();
885      elitesVc.Optimize = true;
886      elitesVc.RangeConstraint.LowerBound = new IntValue(from);
887      elitesVc.RangeConstraint.UpperBound = new IntValue(to);
888      elitesVc.RangeConstraint.StepSize = new IntValue(stepSize);
889    }
890
891    private static void TestOptimization(EngineAlgorithm metaLevelAlgorithm) {
892      string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Results");
893      if (!Directory.Exists(path))
894        Directory.CreateDirectory(path);
895      string id = DateTime.Now.ToString("yyyy.MM.dd - HH;mm;ss,ffff");
896      string resultPath = Path.Combine(path, string.Format("{0} - Result.hl", id));
897      string outputPath = Path.Combine(path, string.Format("{0} - Console.txt", id));
898
899      using (var sw = new StreamWriter(outputPath)) {
900        sw.AutoFlush = true;
901
902        StringBuilder sb1 = new StringBuilder();
903        sb1.AppendFormat("Meta.PopulationSize: {0}\n", metaAlgorithmPopulationSize);
904        sb1.AppendFormat("Meta.MaxGenerations: {0}\n", metaAlgorithmMaxGenerations);
905        sb1.AppendFormat("Meta.Repetitions   : {0}\n", metaProblemRepetitions);
906        sb1.AppendFormat("Meta.MutProb       : {0}\n", ((GeneticAlgorithm)metaLevelAlgorithm).MutationProbability.Value);
907        sb1.AppendFormat("Base.MaxGenerations: {0}\n", baseAlgorithmMaxGenerations);
908        sb1.AppendLine("Problems:");
909        foreach (var prob in ((MetaOptimizationProblem)metaLevelAlgorithm.Problem).Problems) {
910          sb1.Append(prob.Name);
911          var sotf = prob as SingleObjectiveTestFunctionProblem;
912          if (sotf != null) {
913            sb1.AppendFormat(" {0}", sotf.ProblemSize.Value);
914          }
915          sb1.AppendLine();
916        }
917        sw.WriteLine(sb1.ToString());
918        Console.WriteLine(sb1.ToString());
919        metaLevelAlgorithm.Stopped += new EventHandler(metaLevelAlgorithm_Stopped);
920        metaLevelAlgorithm.Paused += new EventHandler(metaLevelAlgorithm_Paused);
921        metaLevelAlgorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(metaLevelAlgorithm_ExceptionOccurred);
922
923        metaLevelAlgorithm.Start();
924        int i = 0;
925        int currentGeneration = -1;
926        do {
927          Thread.Sleep(1000);
928          if (metaLevelAlgorithm.Results.ContainsKey("Generations") && ((IntValue)metaLevelAlgorithm.Results["Generations"].Value).Value != currentGeneration) {
929            while (metaLevelAlgorithm.Results.Count < 6) Thread.Sleep(1000);
930            StringBuilder sb = new StringBuilder();
931            sb.AppendLine(DateTime.Now.ToLongTimeString());
932            sb.AppendLine("=================================");
933
934            sb.AppendLine(metaLevelAlgorithm.ExecutionState.ToString());
935            ResultCollection rsClone = null;
936            while (rsClone == null) {
937              try {
938                rsClone = (ResultCollection)metaLevelAlgorithm.Results.Clone();
939              }
940              catch { }
941            }
942            foreach (var result in rsClone) {
943              sb.AppendLine(result.ToString());
944              if (result.Name == "Population") {
945                RunCollection rc = (RunCollection)result.Value;
946                var orderedRuns = rc.OrderBy(x => x.Results["AverageQualityNormalized"]);
947
948                TableBuilder tb = new TableBuilder("QNorm", "Qualities"/*, "PoSi"*/ ,"MutRa" /*,"Eli", "SelOp"*/, "MutOp"/*, "NrSelSubScopes"*/);
949                foreach (IRun run in orderedRuns) {
950                  //string selector;
951                  //if (run.Parameters["Selector"] is TournamentSelector) {
952                  //  selector = string.Format("{0} ({1})", run.Parameters["Selector"].ToString(), ((TournamentSelector)run.Parameters["Selector"]).GroupSizeParameter.Value.ToString());
953                  //} else {
954                  //  selector = string.Format("{0}", run.Parameters["Selector"].ToString());
955                  //}
956
957                  tb.AppendRow(
958                    ((DoubleValue)run.Results["AverageQualityNormalized"]).Value.ToString("#0.0000")
959                    ,((DoubleArray)run.Results["RunsAverageQualities"]).ToString()
960                    //,((IntValue)run.Parameters["PopulationSize"]).Value.ToString()
961                    ,((DoubleValue)run.Parameters["MutationProbability"]).Value.ToString("0.0000")
962                    //,((IntValue)run.Parameters["Elites"]).Value.ToString()
963                    //,Shorten(selector, 20)
964                    ,Shorten(run.Parameters.ContainsKey("Mutator") ? run.Parameters["Mutator"].ToString() : "null", 40)
965                    //,((ISelector)run.Parameters["Selector"]).NumberOfSelectedSubScopesParameter.Value.ToString()
966                    );
967                }
968                sb.AppendLine(tb.ToString());
969              }
970            } // foreach
971            //Console.Clear();
972            Console.WriteLine(sb.ToString());
973            sw.WriteLine(sb.ToString());
974            currentGeneration = ((IntValue)metaLevelAlgorithm.Results["Generations"].Value).Value;
975          } // if
976          //if (i % 30 == 0) GC.Collect();
977          i++;
978        } while (metaLevelAlgorithm.ExecutionState != ExecutionState.Stopped);
979      }
980
981      Console.WriteLine();
982      Console.WriteLine("Storing...");
983
984      ContentManager.Save((IStorableContent)metaLevelAlgorithm, resultPath, true);
985      Console.WriteLine("Finished");
986    }
987
988    private static void metaLevelAlgorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
989      Console.WriteLine("metaLevelAlgorithm_ExceptionOccurred");
990      Console.WriteLine(e.Value.ToString());
991      if (e.Value.InnerException != null) {
992        Console.WriteLine(e.Value.InnerException.ToString());
993      }
994    }
995
996    private static void metaLevelAlgorithm_Paused(object sender, EventArgs e) {
997      Console.WriteLine("metaLevelAlgorithm_Paused");
998    }
999
1000    private static void metaLevelAlgorithm_Stopped(object sender, EventArgs e) {
1001      Console.WriteLine("metaLevelAlgorithm_Stopped");
1002    }
1003
1004    private static void TestShorten() {
1005      int n = 8;
1006      Console.WriteLine(Shorten("1", n));
1007      Console.WriteLine(Shorten("12", n));
1008      Console.WriteLine(Shorten("123", n));
1009      Console.WriteLine(Shorten("1234", n));
1010      Console.WriteLine(Shorten("12345", n));
1011      Console.WriteLine(Shorten("123456", n));
1012      Console.WriteLine(Shorten("1234567", n));
1013      Console.WriteLine(Shorten("12345678", n));
1014      Console.WriteLine(Shorten("123456789", n));
1015      Console.WriteLine(Shorten("1234567890", n));
1016      Console.WriteLine(Shorten("12345678901", n));
1017    }
1018
1019    private static string Shorten(string s, int n) {
1020      string placeholder = "..";
1021      if (s.Length <= n) return s;
1022      int len = n / 2 - placeholder.Length / 2;
1023      string start = s.Substring(0, len);
1024      string end = s.Substring(s.Length - len, len);
1025      return start + placeholder + end;
1026    }
1027
1028    private static void TestIntSampling() {
1029      System.Random rand = new System.Random();
1030      int lower = 10;
1031      int upper = 20;
1032      int stepsize = 1;
1033      for (int i = 0; i < 100; i++) {
1034        int val;
1035        do {
1036          val = rand.Next(lower / stepsize, upper / stepsize + 1) * stepsize;
1037        } while (val < lower || val > upper);
1038        Console.WriteLine(val);
1039      }
1040    }
1041
1042    private static void TestDoubleSampling() {
1043      System.Random rand = new System.Random();
1044      double lower = 2;
1045      double upper = 3;
1046      double stepsize = 0.6;
1047      for (int i = 0; i < 100; i++) {
1048        double val;
1049        do {
1050          val = Math.Round((rand.NextDouble() * (upper - lower) + lower) / stepsize, 0) * stepsize;
1051        } while (val < lower || val > upper);
1052        Console.WriteLine(val);
1053      }
1054    }
1055
1056    private static IEnumerable<IItem> GetValidValues(IValueParameter valueParameter) {
1057      return ApplicationManager.Manager.GetInstances(valueParameter.DataType).Select(x => (IItem)x).OrderBy(x => x.ItemName);
1058    }
1059  }
1060
1061  public class Node {
1062    public string Name { get; set; }
1063    public int ActualValue { get; set; }
1064    public int[] PossibleValues { get; set; }
1065    public List<Node> ChildNodes { get; set; }
1066
1067    public Node(string name) {
1068      this.Name = name;
1069      PossibleValues = new int[] { 1, 2, 3 };
1070      ChildNodes = new List<Node>();
1071    }
1072
1073    public void Init() {
1074      this.ActualValue = PossibleValues.First();
1075      foreach (var child in ChildNodes) {
1076        child.Init();
1077      }
1078    }
1079
1080    public override string ToString() {
1081      StringBuilder sb = new StringBuilder();
1082      sb.Append(string.Format("{0}:{1}", this.Name, this.ActualValue));
1083      if (this.ChildNodes.Count() > 0) {
1084        sb.Append(" (");
1085        var lst = new List<string>();
1086        foreach (Node child in ChildNodes) {
1087          lst.Add(child.ToString());
1088        }
1089        sb.Append(string.Join(", ", lst.ToArray()));
1090        sb.Append(")");
1091      }
1092
1093      return sb.ToString();
1094    }
1095  }
1096
1097  public class NodeEnumerator : IEnumerator<Node> {
1098    private Node node;
1099    private List<IEnumerator> enumerators;
1100
1101    public NodeEnumerator(Node node) {
1102      this.node = node;
1103      this.enumerators = new List<IEnumerator>();
1104    }
1105
1106    public Node Current {
1107      get { return node; }
1108    }
1109    object IEnumerator.Current {
1110      get { return Current; }
1111    }
1112
1113    public void Dispose() { }
1114
1115    public bool MoveNext() {
1116      int i = 0;
1117      bool ok = false;
1118      while (!ok && i < enumerators.Count) {
1119        if (enumerators[i].MoveNext()) {
1120          ok = true;
1121        } else {
1122          i++;
1123        }
1124      }
1125
1126      if (ok) {
1127        for (int k = i - 1; k >= 0; k--) {
1128          enumerators[k].Reset();
1129          enumerators[k].MoveNext();
1130        }
1131      } else {
1132        return false;
1133      }
1134
1135      node.ActualValue = (int)enumerators[0].Current;
1136      return true;
1137    }
1138
1139    public void Reset() {
1140      enumerators.Clear();
1141      enumerators.Add(node.PossibleValues.GetEnumerator());
1142      enumerators[0].Reset();
1143
1144      foreach (var child in node.ChildNodes) {
1145        var enumerator = new NodeEnumerator(child);
1146        enumerator.Reset();
1147        enumerator.MoveNext();
1148        enumerators.Add(enumerator);
1149      }
1150    }
1151  }
1152}
Note: See TracBrowser for help on using the repository browser.