Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6253 was 6197, checked in by cneumuel, 14 years ago

#1215

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