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
RevLine 
[5144]1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.IO;
[4997]5using System.Linq;
[5144]6using System.Text;
7using System.Threading;
8using HeuristicLab.Algorithms.EvolutionStrategy;
[4997]9using HeuristicLab.Algorithms.GeneticAlgorithm;
[5144]10using HeuristicLab.Common;
[4997]11using HeuristicLab.Core;
[5144]12using HeuristicLab.Data;
13using HeuristicLab.Optimization;
[4997]14using HeuristicLab.PluginInfrastructure;
15using HeuristicLab.Problems.MetaOptimization;
[5144]16using HeuristicLab.Problems.TestFunctions;
[5009]17using HeuristicLab.Random;
[5023]18using HeuristicLab.Selection;
[5184]19using HeuristicLab.Parameters;
[4997]20
21namespace HeuristicLab.MetaOptimization.Test {
22  class Program {
[5184]23    private static int metaAlgorithmPopulationSize = 10;
24    private static int metaAlgorithmMaxGenerations = 10;
25    private static int metaProblemRepetitions = 1;
[5009]26
[5184]27    private static int baseAlgorithmMaxGenerations = 10;
[5009]28
[4997]29    static void Main(string[] args) {
[5087]30      //TestShorten();
31
[4997]32      //TestIntSampling();
33      //TestDoubleSampling();
[5110]34      //TestTypeDiscovery();
[5111]35      //TestOperators();
[5144]36      //TestCombinations();
37      //TestCombinations2();
38      //TestCombinations3();
[5184]39      //TestEnumeratorCollectionEnumerator();
40      //TestCombinations4();
[5144]41
[4997]42      GeneticAlgorithm baseLevelAlgorithm = new GeneticAlgorithm();
[5087]43
[4997]44      MetaOptimizationProblem metaOptimizationProblem = new MetaOptimizationProblem();
[5110]45      metaOptimizationProblem.Repetitions = new IntValue(metaProblemRepetitions);
[5087]46      GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
47      //EvolutionStrategy metaLevelAlgorithm = GetMetaES(metaOptimizationProblem);
[5009]48
[5087]49      IValueConfiguration algorithmVc = SetupGAAlgorithm(baseLevelAlgorithm, metaOptimizationProblem);
[5009]50
[5144]51      //TestToString(algorithmVc);
52
53
[5023]54      //Console.WriteLine("Press enter to start");
55      //Console.ReadLine();
56      //TestConfiguration(algorithmVc, baseLevelAlgorithm);
[5144]57
[5023]58      //Console.WriteLine("Press enter to start");
59      //Console.ReadLine();
[5009]60      TestOptimization(metaLevelAlgorithm);
61
62      //TestMemoryLeak(metaLevelAlgorithm);
63
64      Console.ReadLine();
65    }
66
[5144]67    private static void TestToString(IValueConfiguration algorithmVc) {
68      var random = new MersenneTwister();
[5184]69      Console.WriteLine(algorithmVc.ParameterInfoString);
[5144]70      algorithmVc.Randomize(random);
[5184]71      Console.WriteLine(algorithmVc.ParameterInfoString);
[5144]72      algorithmVc.Randomize(random);
[5184]73      Console.WriteLine(algorithmVc.ParameterInfoString);
[5144]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
[5184]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
[5144]135    private static void TestCombinations4() {
136      GeneticAlgorithm ga = new GeneticAlgorithm();
137      ga.Problem = new SingleObjectiveTestFunctionProblem();
[5184]138      ga.Engine = new SequentialEngine.SequentialEngine();
139
[5144]140      ParameterConfigurationTree vc = new ParameterConfigurationTree(ga);
141
[5184]142      ConfigurePopulationSize(vc, 20, 100, 20);
[5144]143      //ConfigureMutationRate(vc, 0.10, 0.60, 0.10);
[5184]144      //ConfigureMutationOperator(vc);
145      ConfigureSelectionOperator(vc, true);
[5144]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++;
[5184]153        Console.WriteLine(current.ParameterInfoString);
[5144]154      }
155      Console.WriteLine("You are about to create {0} algorithms.", count);
[5184]156     
157      Experiment experiment = vc.GenerateExperiment(ga);
158      //foreach (var opt in experiment.Optimizers) {
159      //  Console.WriteLine(opt.Name);
160      //}
[5144]161
[5184]162      experiment.Prepare();
163      experiment.Start();
164
165      while (experiment.ExecutionState != ExecutionState.Stopped) {
166        Thread.Sleep(500);
[5144]167      }
168    }
169
[5111]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();
[5144]176
[5111]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);
[5144]182
[5111]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
[5110]208    private static void TestTypeDiscovery() {
209      PluginLoader.pluginAssemblies.Any();
[5144]210
[5110]211      var items = ApplicationManager.Manager.GetInstances(typeof(DoubleArray)).ToArray();
212
213      foreach (var item in items) {
214        Console.WriteLine(item.ToString());
215      }
216    }
217
[5009]218    private static void TestMemoryLeak(GeneticAlgorithm metaLevelAlgorithm) {
[5144]219      IValueConfiguration algorithmVc = ((MetaOptimizationProblem)metaLevelAlgorithm.Problem).ParameterConfigurationTree;
[5009]220
221      Console.WriteLine("Starting Memory Test...");
222      Console.ReadLine();
223
[5023]224      var clones = new List<object>();
[5009]225      for (int i = 0; i < 1000; i++) {
226        var clone = algorithmVc.Clone();
[5023]227        clones.Add(clone);
[5009]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
[5087]239    private static GeneticAlgorithm GetMetaGA(MetaOptimizationProblem metaOptimizationProblem) {
[5009]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();
[5184]246     
247      metaLevelAlgorithm.Mutator = ((OptionalConstrainedValueParameter<IManipulator>)((IAlgorithm)metaLevelAlgorithm).Parameters["Mutator"]).ValidValues.Last();
248     
[5023]249      metaLevelAlgorithm.MutationProbability.Value = 0.15;
250
[5009]251      return metaLevelAlgorithm;
252    }
253
[5087]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
[5184]262      metaLevelAlgorithm.Mutator = ((OptionalConstrainedValueParameter<IManipulator>)((IAlgorithm)metaLevelAlgorithm).Parameters["Mutator"]).ValidValues.Last();
[5087]263
264      return metaLevelAlgorithm;
265    }
266
267    private static IValueConfiguration SetupGAAlgorithm(GeneticAlgorithm baseLevelAlgorithm, MetaOptimizationProblem metaOptimizationProblem) {
268      baseLevelAlgorithm.Problem = new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem();
[5009]269      baseLevelAlgorithm.MaximumGenerations.Value = baseAlgorithmMaxGenerations;
270
[4997]271      metaOptimizationProblem.Algorithm = baseLevelAlgorithm;
[5144]272      IValueConfiguration algorithmVc = metaOptimizationProblem.ParameterConfigurationTree;
[4997]273
[5087]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
[5184]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);
[5009]288      return algorithmVc;
289    }
[4997]290
[5009]291    private static void TestConfiguration(IValueConfiguration algorithmVc, GeneticAlgorithm baseLevelAlgorithm) {
[5023]292      IRandom rand = new FastRandom(0);
[4997]293      // set random values
294      for (int i = 0; i < 10; i++) {
295        IValueConfiguration clonedVc = (IValueConfiguration)algorithmVc.Clone();
[5111]296        GeneticAlgorithm newAlg = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
[5009]297        clonedVc.Randomize(rand);
[5111]298        clonedVc.Parameterize(newAlg);
[5009]299        Console.WriteLine(string.Format("PopSize: original: {0}, randomized: {1}", baseLevelAlgorithm.PopulationSize, newAlg.PopulationSize));
[4997]300        Console.WriteLine(string.Format("MutRate: original: {0}, randomized: {1}", baseLevelAlgorithm.MutationProbability, newAlg.MutationProbability));
[5009]301        Console.WriteLine(string.Format("MutOp: original: {0}, randomized: {1}", baseLevelAlgorithm.Mutator, newAlg.Mutator));
[5023]302        Console.WriteLine(string.Format("SelOp: original: {0}, randomized: {1}", baseLevelAlgorithm.Selector, newAlg.Selector));
[5111]303        //Console.WriteLine(string.Format("GrSi: original: {0}, randomized: {1}", "?", ((TournamentSelector)newAlg.Selector).GroupSizeParameter.Value));
[5023]304        Console.WriteLine("---");
[4997]305      }
306
[5023]307      Console.WriteLine("=======================");
308      algorithmVc.Randomize(rand);
309      algorithmVc.Parameterize(baseLevelAlgorithm);
[4997]310      // mutate
311      for (int i = 0; i < 10; i++) {
312        IValueConfiguration clonedVc = (IValueConfiguration)algorithmVc.Clone();
[5111]313        GeneticAlgorithm newAlg = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
314        //clonedVc.Mutate(rand);
[5144]315
[5111]316        //.Apply(rand, clonedVc); todo
317        clonedVc.Parameterize(newAlg);
[5009]318        Console.WriteLine(string.Format("PopSize: original: {0}, mutated: {1}", baseLevelAlgorithm.PopulationSize, newAlg.PopulationSize));
[4997]319        Console.WriteLine(string.Format("MutRate: original: {0}, mutated: {1}", baseLevelAlgorithm.MutationProbability, newAlg.MutationProbability));
[5009]320        Console.WriteLine(string.Format("MutOp: original: {0}, mutated: {1}", baseLevelAlgorithm.Mutator, newAlg.Mutator));
[5023]321        Console.WriteLine(string.Format("SelOp: original: {0}, mutated: {1}", baseLevelAlgorithm.Selector, newAlg.Selector));
[5111]322        //Console.WriteLine(string.Format("GrSi: original: {0}, mutated: {1}", ((TournamentSelector)baseLevelAlgorithm.Selector).GroupSizeParameter.Value, ((TournamentSelector)newAlg.Selector).GroupSizeParameter.Value));
[5023]323        Console.WriteLine("---");
[4997]324      }
325
[5023]326      Console.WriteLine("=======================");
[4997]327      // cross
328      for (int i = 0; i < 10; i++) {
329        IValueConfiguration clonedVc1 = (IValueConfiguration)algorithmVc.Clone();
[5023]330        IValueConfiguration clonedVc2 = (IValueConfiguration)algorithmVc.Clone();
331
[5111]332        GeneticAlgorithm first = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
333        GeneticAlgorithm second = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
[5023]334
[5009]335        clonedVc1.Randomize(rand);
[5023]336        clonedVc1.Parameterize(first);
[4997]337
[5023]338        clonedVc2.Randomize(rand);
339        clonedVc2.Parameterize(second);
[4997]340
341        var popSizeBefore = first.PopulationSize.Value;
342        var mutRateBefore = first.MutationProbability.Value;
[5009]343        var mutOpBefore = first.Mutator;
[5023]344        var selOpBefore = first.Selector;
[5111]345        //var groupSizeBefore = ((TournamentSelector)first.Selector).GroupSizeParameter.Value.Value;
[4997]346
[5111]347        //clonedVc1.Cross(clonedVc2, rand); todo
[5023]348        clonedVc1.Parameterize(first);
[5009]349
350        Console.WriteLine(string.Format("PopSize: first: {0}, second: {1}, crossed: {2}", popSizeBefore, second.PopulationSize, first.PopulationSize));
[4997]351        Console.WriteLine(string.Format("MutRate: first: {0}, second: {1}, crossed: {2}", mutRateBefore, second.MutationProbability, first.MutationProbability));
[5023]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));
[5111]354        //Console.WriteLine(string.Format("GrSi: first: {0}, second: {1}, crossed: {2}", groupSizeBefore, ((TournamentSelector)second.Selector).GroupSizeParameter.Value, ((TournamentSelector)first.Selector).GroupSizeParameter.Value));
[5023]355        Console.WriteLine("---");
[4997]356      }
[5023]357      Console.WriteLine("=======================");
[5009]358    }
[4997]359
[5009]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
[5110]365      var multiMutator = mutationOperator.ValueConfigurations.Where(x => x.ActualValue.Value != null && x.ActualValue.Value.ItemName.StartsWith("Multi")).SingleOrDefault();
[5009]366      if (multiMutator != null) {
367        mutationOperator.ValueConfigurations.SetItemCheckedState(multiMutator, false);
368      }
[4997]369    }
370
[5144]371    private static void ConfigureSelectionOperator(IValueConfiguration algorithmVc, bool configureTournamenSize) {
[5023]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);
[5144]378          if (configureTournamenSize) {
379            vc.Optimize = true;
380            ConfigureTournamentGroupSize(vc);
381          }
[5087]382        } else if (vc.ActualValue.ValueDataType == typeof(RandomSelector)) {
383          selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
[5023]384        } else {
[5087]385          selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
[5023]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;
[5184]395      groupSizePc.ValueConfigurations.First().RangeConstraint.LowerBound = new IntValue(2);
396      groupSizePc.ValueConfigurations.First().RangeConstraint.UpperBound = new IntValue(10);
[5023]397      groupSizePc.ValueConfigurations.First().RangeConstraint.StepSize = new IntValue(1);
398    }
399
[5144]400    private static void ConfigurePopulationSize(IValueConfiguration algorithmVc, int lower, int upper, int stepsize) {
[4997]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;
[5144]405      populationSizeVc.RangeConstraint.LowerBound = new IntValue(lower);
406      populationSizeVc.RangeConstraint.UpperBound = new IntValue(upper);
407      populationSizeVc.RangeConstraint.StepSize = new IntValue(stepsize);
[4997]408    }
409
[5144]410    private static void ConfigureMutationRate(IValueConfiguration algorithmVc, double lower, double upper, double stepsize) {
[4997]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;
[5144]415      mutationRateVc.RangeConstraint.LowerBound = new PercentValue(lower);
416      mutationRateVc.RangeConstraint.UpperBound = new PercentValue(upper);
417      mutationRateVc.RangeConstraint.StepSize = new PercentValue(stepsize);
[4997]418    }
419
[5184]420    private static void ConfigureElites(IValueConfiguration algorithmVc, int from, int to, int stepSize) {
[5023]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;
[5184]425      elitesVc.RangeConstraint.LowerBound = new IntValue(from);
426      elitesVc.RangeConstraint.UpperBound = new IntValue(to);
427      elitesVc.RangeConstraint.StepSize = new IntValue(stepSize);
[5023]428    }
429
[5087]430    private static void TestOptimization(EngineAlgorithm metaLevelAlgorithm) {
[5023]431      ContentManager.Initialize(new PersistenceContentManager());
432      string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Results");
[5087]433      if (!Directory.Exists(path))
[5023]434        Directory.CreateDirectory(path);
[5087]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));
[5023]438
439      using (var sw = new StreamWriter(outputPath)) {
[5087]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());
[5184]449        metaLevelAlgorithm.Stopped += new EventHandler(metaLevelAlgorithm_Stopped);
450        metaLevelAlgorithm.Paused += new EventHandler(metaLevelAlgorithm_Paused);
451        metaLevelAlgorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(metaLevelAlgorithm_ExceptionOccurred);
[5087]452
[5023]453        metaLevelAlgorithm.Start();
454        int i = 0;
455        int currentGeneration = -1;
456        do {
457          Thread.Sleep(500);
[5087]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("=================================");
[5023]463
[5111]464            sb.AppendLine(metaLevelAlgorithm.ExecutionState.ToString());
[5087]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
[5110]471                sb.AppendLine("Qual.  PoSi MutRa Eli SelOp MutOp");
[5087]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());
[5023]478                  }
[5087]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, ' '),
[5110]486                    run.Parameters.ContainsKey("Mutator") ? run.Parameters["Mutator"].ToString() : "null"));
[5023]487                }
[5087]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++;
[5023]497        } while (metaLevelAlgorithm.ExecutionState != ExecutionState.Stopped);
498      }
[5009]499
[5023]500      Console.WriteLine();
501      Console.WriteLine("Storing...");
502
[5087]503      ContentManager.Save((IStorableContent)metaLevelAlgorithm, resultPath, true);
[5009]504      Console.WriteLine("Finished");
505    }
506
[5184]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
[5087]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
[4997]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  }
[5144]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  }
[4997]667}
Note: See TracBrowser for help on using the repository browser.