Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1215

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