Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5576 was 5576, checked in by cneumuel, 12 years ago

#1215

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