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