Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1215

  • enhanced combinations generator (now with batchruns!)
  • fixed ActualNames for metaopt-alg
  • added penalty for invalid solution-candidates (algs which throw exceptions)
  • migrated to .NET 4.0
File size: 28.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;
20
21namespace HeuristicLab.MetaOptimization.Test {
22  class Program {
23    private static int metaAlgorithmPopulationSize = 10;
24    private static int metaAlgorithmMaxGenerations = 10;
25    private static int metaProblemRepetitions = 1;
26
27    private static int baseAlgorithmMaxGenerations = 10;
28
29    static void Main(string[] args) {
30      //TestShorten();
31
32      //TestIntSampling();
33      //TestDoubleSampling();
34      //TestTypeDiscovery();
35      //TestOperators();
36      //TestCombinations();
37      //TestCombinations2();
38      //TestCombinations3();
39      //TestEnumeratorCollectionEnumerator();
40      //TestCombinations4();
41
42      GeneticAlgorithm baseLevelAlgorithm = new GeneticAlgorithm();
43
44      MetaOptimizationProblem metaOptimizationProblem = new MetaOptimizationProblem();
45      metaOptimizationProblem.Repetitions = new IntValue(metaProblemRepetitions);
46      GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
47      //EvolutionStrategy metaLevelAlgorithm = GetMetaES(metaOptimizationProblem);
48
49      IValueConfiguration algorithmVc = SetupGAAlgorithm(baseLevelAlgorithm, metaOptimizationProblem);
50
51      //TestToString(algorithmVc);
52
53
54      //Console.WriteLine("Press enter to start");
55      //Console.ReadLine();
56      //TestConfiguration(algorithmVc, baseLevelAlgorithm);
57
58      //Console.WriteLine("Press enter to start");
59      //Console.ReadLine();
60      TestOptimization(metaLevelAlgorithm);
61
62      //TestMemoryLeak(metaLevelAlgorithm);
63
64      Console.ReadLine();
65    }
66
67    private static void TestToString(IValueConfiguration algorithmVc) {
68      var random = new MersenneTwister();
69      Console.WriteLine(algorithmVc.ParameterInfoString);
70      algorithmVc.Randomize(random);
71      Console.WriteLine(algorithmVc.ParameterInfoString);
72      algorithmVc.Randomize(random);
73      Console.WriteLine(algorithmVc.ParameterInfoString);
74      algorithmVc.Randomize(random);
75    }
76
77    private static void TestCombinations() {
78      Console.WriteLine("IntRange 3-18:3");
79      IntValueRange intRange = new IntValueRange(new IntValue(3), new IntValue(18), new IntValue(3));
80      foreach (var val in intRange.GetCombinations()) {
81        Console.WriteLine(val);
82      }
83
84      Console.WriteLine("DoubleRange 1.0-2.5:0.5");
85      var dblRange = new DoubleValueRange(new DoubleValue(0.7), new DoubleValue(2.8), new DoubleValue(0.5));
86      foreach (var val in dblRange.GetCombinations()) {
87        Console.WriteLine(val);
88      }
89
90      Console.WriteLine("PercentRange 33%-66%:33%");
91      var pctRange = new PercentValueRange(new PercentValue(0.32), new PercentValue(0.98), new PercentValue(0.33));
92      foreach (var val in pctRange.GetCombinations()) {
93        Console.WriteLine(val);
94      }
95    }
96
97    private static void TestCombinations3() {
98      Node root = new Node("root");
99      root.ChildNodes.Add(new Node("root.n1"));
100      root.ChildNodes.Add(new Node("root.n2"));
101      Node n3 = new Node("root.n3");
102      n3.ChildNodes.Add(new Node("root.n3.n1"));
103      n3.ChildNodes.Add(new Node("root.n3.n2"));
104      root.ChildNodes.Add(n3);
105
106      Console.WriteLine(root.ToString());
107      Console.WriteLine("--");
108      int cnt = 0;
109      var enumerator = new NodeEnumerator(root);
110      enumerator.Reset();
111      while (enumerator.MoveNext()) {
112        Console.WriteLine(enumerator.Current.ToString());
113        cnt++;
114      }
115      Console.WriteLine("count: " + cnt);
116    }
117
118    private static void TestEnumeratorCollectionEnumerator() {
119      IEnumerable<int> list1 = new int[] { 1, 2, 3, 4, 5 };
120      IEnumerable<int> list2 = new int[] { 10, 20, 30 };
121      IEnumerable<int> list3 = new int[] { 300, 400, 500 };
122
123      var enumerators = new List<IEnumerator>();
124
125      EnumeratorCollectionEnumerator<int> enu = new EnumeratorCollectionEnumerator<int>();
126      enu.AddEnumerator(list1.GetEnumerator());
127      enu.AddEnumerator(list2.GetEnumerator());
128      enu.AddEnumerator(list3.GetEnumerator());
129      enu.Reset();
130      while (enu.MoveNext()) {
131        Console.WriteLine(enu.Current);
132      }
133    }
134
135    private static void TestCombinations4() {
136      GeneticAlgorithm ga = new GeneticAlgorithm();
137      ga.Problem = new SingleObjectiveTestFunctionProblem();
138      ga.Engine = new SequentialEngine.SequentialEngine();
139
140      ParameterConfigurationTree vc = new ParameterConfigurationTree(ga);
141
142      ConfigurePopulationSize(vc, 20, 100, 20);
143      //ConfigureMutationRate(vc, 0.10, 0.60, 0.10);
144      //ConfigureMutationOperator(vc);
145      ConfigureSelectionOperator(vc, true);
146
147      int count = 0;
148      IEnumerator enumerator = new ParameterCombinationsEnumerator(vc);
149      enumerator.Reset();
150      while (enumerator.MoveNext()) {
151        var current = (IValueConfiguration)enumerator.Current;
152        count++;
153        Console.WriteLine(current.ParameterInfoString);
154      }
155      Console.WriteLine("You are about to create {0} algorithms.", count);
156     
157      Experiment experiment = vc.GenerateExperiment(ga);
158      //foreach (var opt in experiment.Optimizers) {
159      //  Console.WriteLine(opt.Name);
160      //}
161
162      experiment.Prepare();
163      experiment.Start();
164
165      while (experiment.ExecutionState != ExecutionState.Stopped) {
166        Thread.Sleep(500);
167      }
168    }
169
170    private static void TestOperators() {
171      IRandom random = new MersenneTwister();
172      ParameterConfigurationManipulator manip = new ParameterConfigurationManipulator();
173
174      manip.IntValueManipulatorParameter.ActualValue = new UniformIntValueManipulator();
175      manip.DoubleValueManipulatorParameter.ActualValue = new NormalDoubleValueManipulator();
176
177      var doubleRange = new DoubleValueRange(new DoubleValue(0), new DoubleValue(100), new DoubleValue(0.1));
178      using (var sw = new StreamWriter("out-DoubleValue.txt")) {
179        for (int i = 0; i < 10000; i++) {
180          var val = new DoubleValue(50);
181          NormalDoubleValueManipulator.ApplyStatic(random, val, doubleRange);
182
183          sw.WriteLine(val);
184        }
185      }
186
187      var percentRange = new PercentValueRange(new PercentValue(0), new PercentValue(1), new PercentValue(0.001));
188      using (var sw = new StreamWriter("out-PercentValue.txt")) {
189        for (int i = 0; i < 10000; i++) {
190          var val = new PercentValue(0.5);
191          NormalDoubleValueManipulator.ApplyStatic(random, val, percentRange.AsDoubleValueRange());
192          sw.WriteLine(val);
193        }
194      }
195
196      var intRange = new IntValueRange(new IntValue(0), new IntValue(100), new IntValue(1));
197      using (var sw = new StreamWriter("out-IntValue.txt")) {
198        for (int i = 0; i < 10000; i++) {
199          var val = new IntValue(50);
200          UniformIntValueManipulator.ApplyStatic(random, val, intRange);
201          sw.WriteLine(val);
202        }
203      }
204
205      Console.ReadLine();
206    }
207
208    private static void TestTypeDiscovery() {
209      PluginLoader.pluginAssemblies.Any();
210
211      var items = ApplicationManager.Manager.GetInstances(typeof(DoubleArray)).ToArray();
212
213      foreach (var item in items) {
214        Console.WriteLine(item.ToString());
215      }
216    }
217
218    private static void TestMemoryLeak(GeneticAlgorithm metaLevelAlgorithm) {
219      IValueConfiguration algorithmVc = ((MetaOptimizationProblem)metaLevelAlgorithm.Problem).ParameterConfigurationTree;
220
221      Console.WriteLine("Starting Memory Test...");
222      Console.ReadLine();
223
224      var clones = new List<object>();
225      for (int i = 0; i < 1000; i++) {
226        var clone = algorithmVc.Clone();
227        clones.Add(clone);
228      }
229
230      Console.WriteLine("Finished. Now GC...");
231      Console.ReadLine();
232
233      GC.Collect();
234
235      Console.WriteLine("Finished!");
236      Console.ReadLine();
237    }
238
239    private static GeneticAlgorithm GetMetaGA(MetaOptimizationProblem metaOptimizationProblem) {
240      GeneticAlgorithm metaLevelAlgorithm = new GeneticAlgorithm();
241      metaLevelAlgorithm.PopulationSize.Value = metaAlgorithmPopulationSize;
242      metaLevelAlgorithm.MaximumGenerations.Value = metaAlgorithmMaxGenerations;
243
244      metaLevelAlgorithm.Problem = metaOptimizationProblem;
245      metaLevelAlgorithm.Engine = new SequentialEngine.SequentialEngine();
246     
247      metaLevelAlgorithm.Mutator = ((OptionalConstrainedValueParameter<IManipulator>)((IAlgorithm)metaLevelAlgorithm).Parameters["Mutator"]).ValidValues.Last();
248     
249      metaLevelAlgorithm.MutationProbability.Value = 0.15;
250
251      return metaLevelAlgorithm;
252    }
253
254    private static EvolutionStrategy GetMetaES(MetaOptimizationProblem metaOptimizationProblem) {
255      EvolutionStrategy metaLevelAlgorithm = new EvolutionStrategy();
256      metaLevelAlgorithm.PopulationSize.Value = metaAlgorithmPopulationSize;
257      metaLevelAlgorithm.MaximumGenerations.Value = metaAlgorithmMaxGenerations;
258
259      metaLevelAlgorithm.Problem = metaOptimizationProblem;
260      metaLevelAlgorithm.Engine = new SequentialEngine.SequentialEngine();
261
262      metaLevelAlgorithm.Mutator = ((OptionalConstrainedValueParameter<IManipulator>)((IAlgorithm)metaLevelAlgorithm).Parameters["Mutator"]).ValidValues.Last();
263
264      return metaLevelAlgorithm;
265    }
266
267    private static IValueConfiguration SetupGAAlgorithm(GeneticAlgorithm baseLevelAlgorithm, MetaOptimizationProblem metaOptimizationProblem) {
268      baseLevelAlgorithm.Problem = new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem();
269      baseLevelAlgorithm.MaximumGenerations.Value = baseAlgorithmMaxGenerations;
270
271      metaOptimizationProblem.Algorithm = baseLevelAlgorithm;
272      IValueConfiguration algorithmVc = metaOptimizationProblem.ParameterConfigurationTree;
273
274      metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
275        Evaluator = new GriewankEvaluator(),
276        ProblemSize = new IntValue(500)
277      });
278      metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
279        Evaluator = new GriewankEvaluator(),
280        ProblemSize = new IntValue(1000)
281      });
282
283      ConfigurePopulationSize(algorithmVc, 0, 10, 1);
284      //ConfigureMutationRate(algorithmVc, 0.0, 1.0, 0.01);
285      //ConfigureMutationOperator(algorithmVc);
286      ConfigureElites(algorithmVc, 0, 10, 1);
287      //ConfigureSelectionOperator(algorithmVc, true);
288      return algorithmVc;
289    }
290
291    private static void TestConfiguration(IValueConfiguration algorithmVc, GeneticAlgorithm baseLevelAlgorithm) {
292      IRandom rand = new FastRandom(0);
293      // set random values
294      for (int i = 0; i < 10; i++) {
295        IValueConfiguration clonedVc = (IValueConfiguration)algorithmVc.Clone();
296        GeneticAlgorithm newAlg = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
297        clonedVc.Randomize(rand);
298        clonedVc.Parameterize(newAlg);
299        Console.WriteLine(string.Format("PopSize: original: {0}, randomized: {1}", baseLevelAlgorithm.PopulationSize, newAlg.PopulationSize));
300        Console.WriteLine(string.Format("MutRate: original: {0}, randomized: {1}", baseLevelAlgorithm.MutationProbability, newAlg.MutationProbability));
301        Console.WriteLine(string.Format("MutOp: original: {0}, randomized: {1}", baseLevelAlgorithm.Mutator, newAlg.Mutator));
302        Console.WriteLine(string.Format("SelOp: original: {0}, randomized: {1}", baseLevelAlgorithm.Selector, newAlg.Selector));
303        //Console.WriteLine(string.Format("GrSi: original: {0}, randomized: {1}", "?", ((TournamentSelector)newAlg.Selector).GroupSizeParameter.Value));
304        Console.WriteLine("---");
305      }
306
307      Console.WriteLine("=======================");
308      algorithmVc.Randomize(rand);
309      algorithmVc.Parameterize(baseLevelAlgorithm);
310      // mutate
311      for (int i = 0; i < 10; i++) {
312        IValueConfiguration clonedVc = (IValueConfiguration)algorithmVc.Clone();
313        GeneticAlgorithm newAlg = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
314        //clonedVc.Mutate(rand);
315
316        //.Apply(rand, clonedVc); todo
317        clonedVc.Parameterize(newAlg);
318        Console.WriteLine(string.Format("PopSize: original: {0}, mutated: {1}", baseLevelAlgorithm.PopulationSize, newAlg.PopulationSize));
319        Console.WriteLine(string.Format("MutRate: original: {0}, mutated: {1}", baseLevelAlgorithm.MutationProbability, newAlg.MutationProbability));
320        Console.WriteLine(string.Format("MutOp: original: {0}, mutated: {1}", baseLevelAlgorithm.Mutator, newAlg.Mutator));
321        Console.WriteLine(string.Format("SelOp: original: {0}, mutated: {1}", baseLevelAlgorithm.Selector, newAlg.Selector));
322        //Console.WriteLine(string.Format("GrSi: original: {0}, mutated: {1}", ((TournamentSelector)baseLevelAlgorithm.Selector).GroupSizeParameter.Value, ((TournamentSelector)newAlg.Selector).GroupSizeParameter.Value));
323        Console.WriteLine("---");
324      }
325
326      Console.WriteLine("=======================");
327      // cross
328      for (int i = 0; i < 10; i++) {
329        IValueConfiguration clonedVc1 = (IValueConfiguration)algorithmVc.Clone();
330        IValueConfiguration clonedVc2 = (IValueConfiguration)algorithmVc.Clone();
331
332        GeneticAlgorithm first = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
333        GeneticAlgorithm second = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
334
335        clonedVc1.Randomize(rand);
336        clonedVc1.Parameterize(first);
337
338        clonedVc2.Randomize(rand);
339        clonedVc2.Parameterize(second);
340
341        var popSizeBefore = first.PopulationSize.Value;
342        var mutRateBefore = first.MutationProbability.Value;
343        var mutOpBefore = first.Mutator;
344        var selOpBefore = first.Selector;
345        //var groupSizeBefore = ((TournamentSelector)first.Selector).GroupSizeParameter.Value.Value;
346
347        //clonedVc1.Cross(clonedVc2, rand); todo
348        clonedVc1.Parameterize(first);
349
350        Console.WriteLine(string.Format("PopSize: first: {0}, second: {1}, crossed: {2}", popSizeBefore, second.PopulationSize, first.PopulationSize));
351        Console.WriteLine(string.Format("MutRate: first: {0}, second: {1}, crossed: {2}", mutRateBefore, second.MutationProbability, first.MutationProbability));
352        Console.WriteLine(string.Format("MutOp: first: {0}, second: {1}, crossed: {2}", mutOpBefore, second.Mutator, first.Mutator));
353        Console.WriteLine(string.Format("SelOp: first: {0}, second: {1}, crossed: {2}", selOpBefore, second.Selector, first.Selector));
354        //Console.WriteLine(string.Format("GrSi: first: {0}, second: {1}, crossed: {2}", groupSizeBefore, ((TournamentSelector)second.Selector).GroupSizeParameter.Value, ((TournamentSelector)first.Selector).GroupSizeParameter.Value));
355        Console.WriteLine("---");
356      }
357      Console.WriteLine("=======================");
358    }
359
360    private static void ConfigureMutationOperator(IValueConfiguration algorithmVc) {
361      var mutationOperator = algorithmVc.ParameterConfigurations.Where(x => x.Name == "Mutator").SingleOrDefault();
362      mutationOperator.Optimize = true;
363
364      // uncheck multiMutator to avoid Michalewicz issue
365      var multiMutator = mutationOperator.ValueConfigurations.Where(x => x.ActualValue.Value != null && x.ActualValue.Value.ItemName.StartsWith("Multi")).SingleOrDefault();
366      if (multiMutator != null) {
367        mutationOperator.ValueConfigurations.SetItemCheckedState(multiMutator, false);
368      }
369    }
370
371    private static void ConfigureSelectionOperator(IValueConfiguration algorithmVc, bool configureTournamenSize) {
372      var selectionOperatorPc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "Selector").SingleOrDefault();
373      selectionOperatorPc.Optimize = true;
374
375      foreach (var vc in selectionOperatorPc.ValueConfigurations) {
376        if (vc.ActualValue.ValueDataType == typeof(TournamentSelector)) {
377          selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
378          if (configureTournamenSize) {
379            vc.Optimize = true;
380            ConfigureTournamentGroupSize(vc);
381          }
382        } else if (vc.ActualValue.ValueDataType == typeof(RandomSelector)) {
383          selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
384        } else {
385          selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
386        }
387      }
388    }
389
390    private static void ConfigureTournamentGroupSize(IValueConfiguration tournamentVc) {
391      var groupSizePc = tournamentVc.ParameterConfigurations.Where(x => x.ParameterName == "GroupSize").SingleOrDefault();
392      groupSizePc.Optimize = true;
393
394      groupSizePc.ValueConfigurations.First().Optimize = true;
395      groupSizePc.ValueConfigurations.First().RangeConstraint.LowerBound = new IntValue(2);
396      groupSizePc.ValueConfigurations.First().RangeConstraint.UpperBound = new IntValue(10);
397      groupSizePc.ValueConfigurations.First().RangeConstraint.StepSize = new IntValue(1);
398    }
399
400    private static void ConfigurePopulationSize(IValueConfiguration algorithmVc, int lower, int upper, int stepsize) {
401      var populationSizePc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "PopulationSize").SingleOrDefault();
402      populationSizePc.Optimize = true;
403      var populationSizeVc = populationSizePc.ValueConfigurations.First();
404      populationSizeVc.Optimize = true;
405      populationSizeVc.RangeConstraint.LowerBound = new IntValue(lower);
406      populationSizeVc.RangeConstraint.UpperBound = new IntValue(upper);
407      populationSizeVc.RangeConstraint.StepSize = new IntValue(stepsize);
408    }
409
410    private static void ConfigureMutationRate(IValueConfiguration algorithmVc, double lower, double upper, double stepsize) {
411      var mutationRatePc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "MutationProbability").SingleOrDefault();
412      mutationRatePc.Optimize = true;
413      var mutationRateVc = mutationRatePc.ValueConfigurations.First();
414      mutationRateVc.Optimize = true;
415      mutationRateVc.RangeConstraint.LowerBound = new PercentValue(lower);
416      mutationRateVc.RangeConstraint.UpperBound = new PercentValue(upper);
417      mutationRateVc.RangeConstraint.StepSize = new PercentValue(stepsize);
418    }
419
420    private static void ConfigureElites(IValueConfiguration algorithmVc, int from, int to, int stepSize) {
421      var elitesPc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "Elites").SingleOrDefault();
422      elitesPc.Optimize = true;
423      var elitesVc = elitesPc.ValueConfigurations.First();
424      elitesVc.Optimize = true;
425      elitesVc.RangeConstraint.LowerBound = new IntValue(from);
426      elitesVc.RangeConstraint.UpperBound = new IntValue(to);
427      elitesVc.RangeConstraint.StepSize = new IntValue(stepSize);
428    }
429
430    private static void TestOptimization(EngineAlgorithm metaLevelAlgorithm) {
431      ContentManager.Initialize(new PersistenceContentManager());
432      string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Results");
433      if (!Directory.Exists(path))
434        Directory.CreateDirectory(path);
435      string id = DateTime.Now.ToString("yyyy.MM.dd - HH;mm;ss,ffff");
436      string resultPath = Path.Combine(path, string.Format("{0} - Result.hl", id));
437      string outputPath = Path.Combine(path, string.Format("{0} - Console.txt", id));
438
439      using (var sw = new StreamWriter(outputPath)) {
440        sw.AutoFlush = true;
441
442        StringBuilder sb1 = new StringBuilder();
443        sb1.AppendLine(string.Format("Meta.PopulationSize: {0}", metaAlgorithmPopulationSize));
444        sb1.AppendLine(string.Format("Meta.MaxGenerations: {0}", metaAlgorithmMaxGenerations));
445        sb1.AppendLine(string.Format("Meta.Repetitions   : {0}", metaProblemRepetitions));
446        sb1.AppendLine(string.Format("Base.MaxGenerations: {0}", baseAlgorithmMaxGenerations));
447        sw.WriteLine(sb1.ToString());
448        Console.WriteLine(sb1.ToString());
449        metaLevelAlgorithm.Stopped += new EventHandler(metaLevelAlgorithm_Stopped);
450        metaLevelAlgorithm.Paused += new EventHandler(metaLevelAlgorithm_Paused);
451        metaLevelAlgorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(metaLevelAlgorithm_ExceptionOccurred);
452
453        metaLevelAlgorithm.Start();
454        int i = 0;
455        int currentGeneration = -1;
456        do {
457          Thread.Sleep(500);
458          if (metaLevelAlgorithm.Results.ContainsKey("Generations") && ((IntValue)metaLevelAlgorithm.Results["Generations"].Value).Value != currentGeneration) {
459            while (metaLevelAlgorithm.Results.Count < 3) Thread.Sleep(100);
460            StringBuilder sb = new StringBuilder();
461            sb.AppendLine(DateTime.Now.ToLongTimeString());
462            sb.AppendLine("=================================");
463
464            sb.AppendLine(metaLevelAlgorithm.ExecutionState.ToString());
465            foreach (var result in metaLevelAlgorithm.Results) {
466              sb.AppendLine(result.ToString());
467              if (result.Name == "Population") {
468                RunCollection rc = (RunCollection)result.Value;
469                var orderedRuns = rc.OrderBy(x => x.Results["RunsAverageQuality"]);
470
471                sb.AppendLine("Qual.  PoSi MutRa Eli SelOp MutOp");
472                foreach (IRun run in orderedRuns) {
473                  string selector;
474                  if (run.Parameters["Selector"] is TournamentSelector) {
475                    selector = string.Format("{0} ({1})", run.Parameters["Selector"].ToString(), ((TournamentSelector)run.Parameters["Selector"]).GroupSizeParameter.Value.ToString());
476                  } else {
477                    selector = string.Format("{0}", run.Parameters["Selector"].ToString());
478                  }
479
480                  sb.AppendLine(string.Format("{0} {1} {2} {3} {4} {5}",
481                    ((DoubleValue)run.Results["RunsAverageQuality"]).Value.ToString("#0.00").PadLeft(7, ' '),
482                    ((IntValue)run.Parameters["PopulationSize"]).Value.ToString().PadLeft(3, ' ').PadRight(3, ' '),
483                    ((DoubleValue)run.Parameters["MutationProbability"]).Value.ToString("0.00").PadLeft(5, ' '),
484                    ((IntValue)run.Parameters["Elites"]).Value.ToString().PadLeft(3, ' '),
485                    Shorten(selector, 20).PadRight(20, ' '),
486                    run.Parameters.ContainsKey("Mutator") ? run.Parameters["Mutator"].ToString() : "null"));
487                }
488              }
489            } // foreach
490            Console.Clear();
491            Console.WriteLine(sb.ToString());
492            sw.WriteLine(sb.ToString());
493            currentGeneration = ((IntValue)metaLevelAlgorithm.Results["Generations"].Value).Value;
494          } // if
495          if (i % 30 == 0) GC.Collect();
496          i++;
497        } while (metaLevelAlgorithm.ExecutionState != ExecutionState.Stopped);
498      }
499
500      Console.WriteLine();
501      Console.WriteLine("Storing...");
502
503      ContentManager.Save((IStorableContent)metaLevelAlgorithm, resultPath, true);
504      Console.WriteLine("Finished");
505    }
506
507    private static void metaLevelAlgorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
508      Console.WriteLine("metaLevelAlgorithm_ExceptionOccurred");
509    }
510
511    private static void metaLevelAlgorithm_Paused(object sender, EventArgs e) {
512      Console.WriteLine("metaLevelAlgorithm_Paused");
513    }
514
515    private static void metaLevelAlgorithm_Stopped(object sender, EventArgs e) {
516      Console.WriteLine("metaLevelAlgorithm_Stopped");
517    }
518
519    private static void TestShorten() {
520      int n = 8;
521      Console.WriteLine(Shorten("1", n));
522      Console.WriteLine(Shorten("12", n));
523      Console.WriteLine(Shorten("123", n));
524      Console.WriteLine(Shorten("1234", n));
525      Console.WriteLine(Shorten("12345", n));
526      Console.WriteLine(Shorten("123456", n));
527      Console.WriteLine(Shorten("1234567", n));
528      Console.WriteLine(Shorten("12345678", n));
529      Console.WriteLine(Shorten("123456789", n));
530      Console.WriteLine(Shorten("1234567890", n));
531      Console.WriteLine(Shorten("12345678901", n));
532    }
533
534    private static string Shorten(string s, int n) {
535      string placeholder = "..";
536      if (s.Length <= n) return s;
537      int len = n / 2 - placeholder.Length / 2;
538      string start = s.Substring(0, len);
539      string end = s.Substring(s.Length - len, len);
540      return start + placeholder + end;
541    }
542
543    private static void TestIntSampling() {
544      System.Random rand = new System.Random();
545      int lower = 10;
546      int upper = 20;
547      int stepsize = 7;
548      for (int i = 0; i < 100; i++) {
549        int val;
550        do {
551          val = rand.Next(lower / stepsize, upper / stepsize + 1) * stepsize;
552        } while (val < lower || val > upper);
553        Console.WriteLine(val);
554      }
555    }
556
557    private static void TestDoubleSampling() {
558      System.Random rand = new System.Random();
559      double lower = 2;
560      double upper = 3;
561      double stepsize = 0.6;
562      for (int i = 0; i < 100; i++) {
563        double val;
564        do {
565          val = Math.Round((rand.NextDouble() * (upper - lower) + lower) / stepsize, 0) * stepsize;
566        } while (val < lower || val > upper);
567        Console.WriteLine(val);
568      }
569    }
570
571    private static IEnumerable<IItem> GetValidValues(IValueParameter valueParameter) {
572      return ApplicationManager.Manager.GetInstances(valueParameter.DataType).Select(x => (IItem)x).OrderBy(x => x.ItemName);
573    }
574  }
575
576  public class Node {
577    public string Name { get; set; }
578    public int ActualValue { get; set; }
579    public int[] PossibleValues { get; set; }
580    public List<Node> ChildNodes { get; set; }
581
582    public Node(string name) {
583      this.Name = name;
584      PossibleValues = new int[] { 1, 2, 3 };
585      ChildNodes = new List<Node>();
586    }
587
588    public void Init() {
589      this.ActualValue = PossibleValues.First();
590      foreach (var child in ChildNodes) {
591        child.Init();
592      }
593    }
594
595    public override string ToString() {
596      StringBuilder sb = new StringBuilder();
597      sb.Append(string.Format("{0}:{1}", this.Name, this.ActualValue));
598      if (this.ChildNodes.Count() > 0) {
599        sb.Append(" (");
600        var lst = new List<string>();
601        foreach (Node child in ChildNodes) {
602          lst.Add(child.ToString());
603        }
604        sb.Append(string.Join(", ", lst.ToArray()));
605        sb.Append(")");
606      }
607
608      return sb.ToString();
609    }
610  }
611
612  public class NodeEnumerator : IEnumerator<Node> {
613    private Node node;
614    private List<IEnumerator> enumerators;
615
616    public NodeEnumerator(Node node) {
617      this.node = node;
618      this.enumerators = new List<IEnumerator>();
619    }
620
621    public Node Current {
622      get { return node; }
623    }
624    object IEnumerator.Current {
625      get { return Current; }
626    }
627
628    public void Dispose() { }
629
630    public bool MoveNext() {
631      int i = 0;
632      bool ok = false;
633      while(!ok && i < enumerators.Count) {
634        if(enumerators[i].MoveNext()) {
635          ok = true;
636        } else {
637          i++;
638        }
639      }
640
641      if (ok) {
642        for (int k = i-1; k >= 0; k--) {
643          enumerators[k].Reset();
644          enumerators[k].MoveNext();
645        }
646      } else {
647        return false;
648      }
649
650      node.ActualValue = (int)enumerators[0].Current;
651      return true;
652    }
653
654    public void Reset() {
655      enumerators.Clear();
656      enumerators.Add(node.PossibleValues.GetEnumerator());
657      enumerators[0].Reset();
658
659      foreach (var child in node.ChildNodes) {
660        var enumerator = new NodeEnumerator(child);
661        enumerator.Reset();
662        enumerator.MoveNext();
663        enumerators.Add(enumerator);
664      }
665    }
666  }
667}
Note: See TracBrowser for help on using the repository browser.