Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6055 was 6038, checked in by cneumuel, 14 years ago

#1215

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