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