1 | using System;
|
---|
2 | using System.Collections;
|
---|
3 | using System.Collections.Generic;
|
---|
4 | using System.IO;
|
---|
5 | using System.Linq;
|
---|
6 | using System.Text;
|
---|
7 | using System.Threading;
|
---|
8 | using HeuristicLab.Algorithms.EvolutionStrategy;
|
---|
9 | using HeuristicLab.Algorithms.GeneticAlgorithm;
|
---|
10 | using HeuristicLab.Common;
|
---|
11 | using HeuristicLab.Core;
|
---|
12 | using HeuristicLab.Data;
|
---|
13 | using HeuristicLab.Optimization;
|
---|
14 | using HeuristicLab.PluginInfrastructure;
|
---|
15 | using HeuristicLab.Problems.MetaOptimization;
|
---|
16 | using HeuristicLab.Problems.TestFunctions;
|
---|
17 | using HeuristicLab.Random;
|
---|
18 | using HeuristicLab.Selection;
|
---|
19 | using HeuristicLab.Parameters;
|
---|
20 | using HeuristicLab.Operators;
|
---|
21 | using System.Diagnostics;
|
---|
22 | using HeuristicLab.Encodings.RealVectorEncoding;
|
---|
23 | using HeuristicLab.Hive.ExperimentManager;
|
---|
24 | using System.Threading.Tasks;
|
---|
25 |
|
---|
26 | namespace HeuristicLab.MetaOptimization.Test {
|
---|
27 | class Program {
|
---|
28 | //private static int metaAlgorithmPopulationSize = 50;
|
---|
29 | //private static int metaAlgorithmMaxGenerations = 30;
|
---|
30 | //private static int metaProblemRepetitions = 5;
|
---|
31 | //private static int baseAlgorithmMaxGenerations = 1000;
|
---|
32 |
|
---|
33 | private static int metaAlgorithmPopulationSize = 10;
|
---|
34 | private static int metaAlgorithmMaxGenerations = 20;
|
---|
35 | private static int metaProblemRepetitions = 3;
|
---|
36 | private static int baseAlgorithmMaxGenerations = 10;
|
---|
37 |
|
---|
38 | static void Main(string[] args) {
|
---|
39 | //TestTableBuilder();
|
---|
40 | //TestShorten();
|
---|
41 |
|
---|
42 | //TestIntSampling();
|
---|
43 | //TestDoubleSampling(); return;
|
---|
44 | //TestTypeDiscovery();
|
---|
45 | //TestOperators();
|
---|
46 | //TestCombinations();
|
---|
47 | //TestCombinations2();
|
---|
48 | //TestCombinations3();
|
---|
49 | //TestEnumeratorCollectionEnumerator();
|
---|
50 | //TestCombinations4();
|
---|
51 | //TestAlgorithmPerformanceIssue();
|
---|
52 | TestWaitAny();
|
---|
53 |
|
---|
54 | GeneticAlgorithm baseLevelAlgorithm = new GeneticAlgorithm();
|
---|
55 |
|
---|
56 | MetaOptimizationProblem metaOptimizationProblem = new MetaOptimizationProblem();
|
---|
57 | metaOptimizationProblem.Repetitions = new IntValue(metaProblemRepetitions);
|
---|
58 | GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
|
---|
59 | //GeneticAlgorithm metaLevelAlgorithm = GetParallelMetaGA(metaOptimizationProblem);
|
---|
60 | //GeneticAlgorithm metaLevelAlgorithm = GetHiveParallelMetaGA(metaOptimizationProblem);
|
---|
61 |
|
---|
62 | //EvolutionStrategy metaLevelAlgorithm = GetMetaES(metaOptimizationProblem);
|
---|
63 |
|
---|
64 | IValueConfiguration algorithmVc = SetupGAAlgorithm(baseLevelAlgorithm, metaOptimizationProblem);
|
---|
65 |
|
---|
66 | //TestToString(algorithmVc);
|
---|
67 |
|
---|
68 |
|
---|
69 | //Console.WriteLine("Press enter to start");
|
---|
70 | //Console.ReadLine();
|
---|
71 | //TestConfiguration(algorithmVc, baseLevelAlgorithm);
|
---|
72 |
|
---|
73 | //Console.WriteLine("Press enter to start");
|
---|
74 | //Console.ReadLine();
|
---|
75 | TestOptimization(metaLevelAlgorithm);
|
---|
76 |
|
---|
77 | //TestMemoryLeak(metaLevelAlgorithm);
|
---|
78 |
|
---|
79 | Console.ReadLine();
|
---|
80 | }
|
---|
81 |
|
---|
82 | private static void TestWaitAny() {
|
---|
83 | System.Random rand = new System.Random();
|
---|
84 | var tasks = new List<Task<int>>();
|
---|
85 | for (int i = 0; i < 10; i++) {
|
---|
86 | tasks.Add(Task.Factory.StartNew<int>((x) => {
|
---|
87 | int sleep = ((int)x - 10) * -1000;
|
---|
88 | Console.WriteLine("sleeping: {0} ms", sleep);
|
---|
89 | Thread.Sleep(0); // make context switch
|
---|
90 | Thread.Sleep(sleep);
|
---|
91 | return (int)x * (int)x;
|
---|
92 | }, i));
|
---|
93 | }
|
---|
94 |
|
---|
95 | // --> WaitAll processes tasks lazy but in order.
|
---|
96 | Task.WaitAll();
|
---|
97 | foreach (var task in tasks) {
|
---|
98 | Console.WriteLine(task.Result);
|
---|
99 | }
|
---|
100 |
|
---|
101 | // -> WaitAny processes any finished task first. but the finished task needs to be removed from list in order to process all tasks
|
---|
102 | //for (int i = 0; i < 10; i++) {
|
---|
103 | // var tasksArray = tasks.ToArray();
|
---|
104 | // var task = tasksArray[Task.WaitAny(tasksArray)];
|
---|
105 | // Console.WriteLine(task.Result);
|
---|
106 | // tasks.Remove(task);
|
---|
107 | //}
|
---|
108 |
|
---|
109 | Console.WriteLine("Finished TestWaitAny");
|
---|
110 | }
|
---|
111 |
|
---|
112 | private static void TestAlgorithmPerformanceIssue() {
|
---|
113 | ContentManager.Initialize(new PersistenceContentManager());
|
---|
114 | Queue<TimeSpan> latestExecutionTimes = new Queue<TimeSpan>();
|
---|
115 | int size = 10;
|
---|
116 |
|
---|
117 | GeneticAlgorithm ga = new GeneticAlgorithm();
|
---|
118 | ga.PopulationSize.Value = 3;
|
---|
119 | ga.MaximumGenerations.Value = 1;
|
---|
120 | ga.Engine = new SequentialEngine.SequentialEngine();
|
---|
121 |
|
---|
122 | MetaOptimizationProblem metaOptimizationProblem = new MetaOptimizationProblem();
|
---|
123 | metaOptimizationProblem.Repetitions = new IntValue(metaProblemRepetitions);
|
---|
124 | GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
|
---|
125 | ParameterConfigurationTree algorithmVc = SetupGAAlgorithm(ga, metaOptimizationProblem);
|
---|
126 | Stopwatch sw = new Stopwatch();
|
---|
127 |
|
---|
128 | for (int i = 0; i < 1000; i++) {
|
---|
129 | sw.Start();
|
---|
130 | GeneticAlgorithm clonedGa = (GeneticAlgorithm)ga.Clone();
|
---|
131 | clonedGa.Name = "CLONED GA";
|
---|
132 | algorithmVc.Parameterize(clonedGa);
|
---|
133 | clonedGa.Prepare(true);
|
---|
134 | var executor = new AlgorithmExecutor(clonedGa);
|
---|
135 | executor.StartSync();
|
---|
136 | sw.Stop();
|
---|
137 | latestExecutionTimes.Enqueue(sw.Elapsed);
|
---|
138 | Console.WriteLine("{0}: {1} ({2})", i, sw.Elapsed, latestExecutionTimes.Count > size ? TimeSpan.FromMilliseconds(latestExecutionTimes.Average(t => t.TotalMilliseconds)).ToString() : "-");
|
---|
139 | if (latestExecutionTimes.Count > size) {
|
---|
140 | latestExecutionTimes.Dequeue();
|
---|
141 | }
|
---|
142 | sw.Reset();
|
---|
143 | }
|
---|
144 | }
|
---|
145 |
|
---|
146 | private static void TestTableBuilder() {
|
---|
147 | TableBuilder tb = new TableBuilder("column_1", "col2", "col3");
|
---|
148 | tb.AppendRow("1", "humpi", "0.23124");
|
---|
149 | tb.AppendRow("2", "sf", "0.23124");
|
---|
150 | tb.AppendRow("5", "humpi dampti", "0.224");
|
---|
151 | tb.AppendRow("10", "egon asdf", "0.4");
|
---|
152 | tb.AppendRow("15", "MichaelizcMultiVfds", "0.23124564");
|
---|
153 | Console.WriteLine(tb.ToString());
|
---|
154 | }
|
---|
155 |
|
---|
156 | private static void TestToInfoString(IValueConfiguration algorithmVc) {
|
---|
157 | var random = new MersenneTwister();
|
---|
158 | Console.WriteLine(algorithmVc.ParameterInfoString);
|
---|
159 | algorithmVc.Randomize(random);
|
---|
160 | Console.WriteLine(algorithmVc.ParameterInfoString);
|
---|
161 | algorithmVc.Randomize(random);
|
---|
162 | Console.WriteLine(algorithmVc.ParameterInfoString);
|
---|
163 | algorithmVc.Randomize(random);
|
---|
164 | }
|
---|
165 |
|
---|
166 | private static void TestCombinations() {
|
---|
167 | Console.WriteLine("IntRange 3-18:3");
|
---|
168 | IntValueRange intRange = new IntValueRange(new IntValue(3), new IntValue(18), new IntValue(3));
|
---|
169 | foreach (var val in intRange.GetCombinations()) {
|
---|
170 | Console.WriteLine(val);
|
---|
171 | }
|
---|
172 |
|
---|
173 | Console.WriteLine("DoubleRange 1.0-2.5:0.5");
|
---|
174 | var dblRange = new DoubleValueRange(new DoubleValue(0.7), new DoubleValue(2.8), new DoubleValue(0.5));
|
---|
175 | foreach (var val in dblRange.GetCombinations()) {
|
---|
176 | Console.WriteLine(val);
|
---|
177 | }
|
---|
178 |
|
---|
179 | Console.WriteLine("PercentRange 33%-66%:33%");
|
---|
180 | var pctRange = new PercentValueRange(new PercentValue(0.32), new PercentValue(0.98), new PercentValue(0.33));
|
---|
181 | foreach (var val in pctRange.GetCombinations()) {
|
---|
182 | Console.WriteLine(val);
|
---|
183 | }
|
---|
184 | }
|
---|
185 |
|
---|
186 | private static void TestCombinations3() {
|
---|
187 | Node root = new Node("root");
|
---|
188 | root.ChildNodes.Add(new Node("root.n1"));
|
---|
189 | root.ChildNodes.Add(new Node("root.n2"));
|
---|
190 | Node n3 = new Node("root.n3");
|
---|
191 | n3.ChildNodes.Add(new Node("root.n3.n1"));
|
---|
192 | n3.ChildNodes.Add(new Node("root.n3.n2"));
|
---|
193 | root.ChildNodes.Add(n3);
|
---|
194 |
|
---|
195 | Console.WriteLine(root.ToString());
|
---|
196 | Console.WriteLine("--");
|
---|
197 | int cnt = 0;
|
---|
198 | var enumerator = new NodeEnumerator(root);
|
---|
199 | enumerator.Reset();
|
---|
200 | while (enumerator.MoveNext()) {
|
---|
201 | Console.WriteLine(enumerator.Current.ToString());
|
---|
202 | cnt++;
|
---|
203 | }
|
---|
204 | Console.WriteLine("count: " + cnt);
|
---|
205 | }
|
---|
206 |
|
---|
207 | private static void TestEnumeratorCollectionEnumerator() {
|
---|
208 | IEnumerable<int> list1 = new int[] { 1, 2, 3, 4, 5 };
|
---|
209 | IEnumerable<int> list2 = new int[] { 10, 20, 30 };
|
---|
210 | IEnumerable<int> list3 = new int[] { 300, 400, 500 };
|
---|
211 |
|
---|
212 | var enumerators = new List<IEnumerator>();
|
---|
213 |
|
---|
214 | EnumeratorCollectionEnumerator<int> enu = new EnumeratorCollectionEnumerator<int>();
|
---|
215 | enu.AddEnumerator(list1.GetEnumerator());
|
---|
216 | enu.AddEnumerator(list2.GetEnumerator());
|
---|
217 | enu.AddEnumerator(list3.GetEnumerator());
|
---|
218 | enu.Reset();
|
---|
219 | while (enu.MoveNext()) {
|
---|
220 | Console.WriteLine(enu.Current);
|
---|
221 | }
|
---|
222 | }
|
---|
223 |
|
---|
224 | private static void TestCombinations4() {
|
---|
225 | GeneticAlgorithm ga = new GeneticAlgorithm();
|
---|
226 | ga.Problem = new SingleObjectiveTestFunctionProblem();
|
---|
227 | ga.Engine = new SequentialEngine.SequentialEngine();
|
---|
228 |
|
---|
229 | ParameterConfigurationTree vc = new ParameterConfigurationTree(ga);
|
---|
230 |
|
---|
231 | ConfigurePopulationSize(vc, 20, 100, 20);
|
---|
232 | //ConfigureMutationRate(vc, 0.10, 0.60, 0.10);
|
---|
233 | //ConfigureMutationOperator(vc);
|
---|
234 | ConfigureSelectionOperator(vc, true);
|
---|
235 |
|
---|
236 | int count = 0;
|
---|
237 | IEnumerator enumerator = new ParameterCombinationsEnumerator(vc);
|
---|
238 | enumerator.Reset();
|
---|
239 | while (enumerator.MoveNext()) {
|
---|
240 | var current = (IValueConfiguration)enumerator.Current;
|
---|
241 | count++;
|
---|
242 | Console.WriteLine(current.ParameterInfoString);
|
---|
243 | }
|
---|
244 | Console.WriteLine("You are about to create {0} algorithms.", count);
|
---|
245 |
|
---|
246 | Experiment experiment = vc.GenerateExperiment(ga);
|
---|
247 | //foreach (var opt in experiment.Optimizers) {
|
---|
248 | // Console.WriteLine(opt.Name);
|
---|
249 | //}
|
---|
250 |
|
---|
251 | experiment.Prepare();
|
---|
252 | experiment.Start();
|
---|
253 |
|
---|
254 | while (experiment.ExecutionState != ExecutionState.Stopped) {
|
---|
255 | Thread.Sleep(500);
|
---|
256 | }
|
---|
257 | }
|
---|
258 |
|
---|
259 | private static void TestOperators() {
|
---|
260 | IRandom random = new MersenneTwister();
|
---|
261 |
|
---|
262 | var doubleRange = new DoubleValueRange(new DoubleValue(0), new DoubleValue(100), new DoubleValue(0.1));
|
---|
263 | using (var sw = new StreamWriter("out-DoubleValue.txt")) {
|
---|
264 | for (int i = 0; i < 10000; i++) {
|
---|
265 | var val = new DoubleValue(90);
|
---|
266 | NormalDoubleValueManipulator.ApplyStatic(random, val, doubleRange);
|
---|
267 |
|
---|
268 | sw.WriteLine(val);
|
---|
269 | }
|
---|
270 | }
|
---|
271 |
|
---|
272 | var percentRange = new PercentValueRange(new PercentValue(0), new PercentValue(1), new PercentValue(0.001));
|
---|
273 | using (var sw = new StreamWriter("out-PercentValue.txt")) {
|
---|
274 | for (int i = 0; i < 10000; i++) {
|
---|
275 | var val = new PercentValue(0.5);
|
---|
276 | NormalDoubleValueManipulator.ApplyStatic(random, val, percentRange.AsDoubleValueRange());
|
---|
277 | sw.WriteLine(val);
|
---|
278 | }
|
---|
279 | }
|
---|
280 |
|
---|
281 | var intRange = new IntValueRange(new IntValue(0), new IntValue(100), new IntValue(1));
|
---|
282 | using (var sw = new StreamWriter("out-IntValue.txt")) {
|
---|
283 | for (int i = 0; i < 10000; i++) {
|
---|
284 | var val = new IntValue(50);
|
---|
285 | UniformIntValueManipulator.ApplyStatic(random, val, intRange);
|
---|
286 | sw.WriteLine(val);
|
---|
287 | }
|
---|
288 | }
|
---|
289 |
|
---|
290 | Console.ReadLine();
|
---|
291 | }
|
---|
292 |
|
---|
293 | private static void TestTypeDiscovery() {
|
---|
294 | PluginLoader.pluginAssemblies.Any();
|
---|
295 |
|
---|
296 | var items = ApplicationManager.Manager.GetInstances(typeof(DoubleArray)).ToArray();
|
---|
297 |
|
---|
298 | foreach (var item in items) {
|
---|
299 | Console.WriteLine(item.ToString());
|
---|
300 | }
|
---|
301 | }
|
---|
302 |
|
---|
303 | private static void TestMemoryLeak(GeneticAlgorithm metaLevelAlgorithm) {
|
---|
304 | IValueConfiguration algorithmVc = ((MetaOptimizationProblem)metaLevelAlgorithm.Problem).ParameterConfigurationTree;
|
---|
305 |
|
---|
306 | Console.WriteLine("Starting Memory Test...");
|
---|
307 | Console.ReadLine();
|
---|
308 |
|
---|
309 | var clones = new List<object>();
|
---|
310 | for (int i = 0; i < 1000; i++) {
|
---|
311 | var clone = algorithmVc.Clone();
|
---|
312 | clones.Add(clone);
|
---|
313 | }
|
---|
314 |
|
---|
315 | Console.WriteLine("Finished. Now GC...");
|
---|
316 | Console.ReadLine();
|
---|
317 |
|
---|
318 | GC.Collect();
|
---|
319 |
|
---|
320 | Console.WriteLine("Finished!");
|
---|
321 | Console.ReadLine();
|
---|
322 | }
|
---|
323 |
|
---|
324 | private static GeneticAlgorithm GetMetaGA(MetaOptimizationProblem metaOptimizationProblem) {
|
---|
325 | GeneticAlgorithm metaLevelAlgorithm = new GeneticAlgorithm();
|
---|
326 | metaLevelAlgorithm.PopulationSize.Value = metaAlgorithmPopulationSize;
|
---|
327 | metaLevelAlgorithm.MaximumGenerations.Value = metaAlgorithmMaxGenerations;
|
---|
328 |
|
---|
329 | metaLevelAlgorithm.Problem = metaOptimizationProblem;
|
---|
330 | metaLevelAlgorithm.Engine = new SequentialEngine.SequentialEngine();
|
---|
331 |
|
---|
332 | metaLevelAlgorithm.Mutator = ((OptionalConstrainedValueParameter<IManipulator>)((IAlgorithm)metaLevelAlgorithm).Parameters["Mutator"]).ValidValues.Last();
|
---|
333 |
|
---|
334 | metaLevelAlgorithm.MutationProbability.Value = 0.15;
|
---|
335 |
|
---|
336 | return metaLevelAlgorithm;
|
---|
337 | }
|
---|
338 |
|
---|
339 | private static GeneticAlgorithm GetParallelMetaGA(MetaOptimizationProblem metaOptimizationProblem) {
|
---|
340 | GeneticAlgorithm metaLevelAlgorithm = GetMetaGA(metaOptimizationProblem);
|
---|
341 | metaLevelAlgorithm.Engine = new ParallelEngine.ParallelEngine();
|
---|
342 | return metaLevelAlgorithm;
|
---|
343 | }
|
---|
344 |
|
---|
345 | private static GeneticAlgorithm GetHiveParallelMetaGA(MetaOptimizationProblem metaOptimizationProblem) {
|
---|
346 | GeneticAlgorithm metaLevelAlgorithm = GetParallelMetaGA(metaOptimizationProblem);
|
---|
347 | metaLevelAlgorithm.Engine = new HiveEngine.HiveEngine();
|
---|
348 | ServiceLocator.Instance.ClientFacadePool.UserName = "cneumuel";
|
---|
349 | ServiceLocator.Instance.ClientFacadePool.Password = "cneumuel";
|
---|
350 | ServiceLocator.Instance.StreamedClientFacadePool.UserName = "cneumuel";
|
---|
351 | ServiceLocator.Instance.StreamedClientFacadePool.Password = "cneumuel";
|
---|
352 | return metaLevelAlgorithm;
|
---|
353 | }
|
---|
354 |
|
---|
355 | private static EvolutionStrategy GetMetaES(MetaOptimizationProblem metaOptimizationProblem) {
|
---|
356 | EvolutionStrategy metaLevelAlgorithm = new EvolutionStrategy();
|
---|
357 | metaLevelAlgorithm.PopulationSize.Value = metaAlgorithmPopulationSize;
|
---|
358 | metaLevelAlgorithm.MaximumGenerations.Value = metaAlgorithmMaxGenerations;
|
---|
359 |
|
---|
360 | metaLevelAlgorithm.Problem = metaOptimizationProblem;
|
---|
361 | metaLevelAlgorithm.Engine = new SequentialEngine.SequentialEngine();
|
---|
362 |
|
---|
363 | metaLevelAlgorithm.Mutator = ((OptionalConstrainedValueParameter<IManipulator>)((IAlgorithm)metaLevelAlgorithm).Parameters["Mutator"]).ValidValues.Last();
|
---|
364 |
|
---|
365 | return metaLevelAlgorithm;
|
---|
366 | }
|
---|
367 |
|
---|
368 | private static ParameterConfigurationTree SetupGAAlgorithm(GeneticAlgorithm baseLevelAlgorithm, MetaOptimizationProblem metaOptimizationProblem) {
|
---|
369 | baseLevelAlgorithm.Problem = new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem();
|
---|
370 | baseLevelAlgorithm.MaximumGenerations.Value = baseAlgorithmMaxGenerations;
|
---|
371 |
|
---|
372 | metaOptimizationProblem.Algorithm = baseLevelAlgorithm;
|
---|
373 | ParameterConfigurationTree algorithmVc = metaOptimizationProblem.ParameterConfigurationTree;
|
---|
374 |
|
---|
375 | metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
|
---|
376 | Evaluator = new GriewankEvaluator(),
|
---|
377 | ProblemSize = new IntValue(5)
|
---|
378 | });
|
---|
379 | metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
|
---|
380 | Evaluator = new GriewankEvaluator(),
|
---|
381 | ProblemSize = new IntValue(50)
|
---|
382 | });
|
---|
383 | metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
|
---|
384 | Evaluator = new GriewankEvaluator(),
|
---|
385 | ProblemSize = new IntValue(500)
|
---|
386 | });
|
---|
387 |
|
---|
388 | ConfigurePopulationSize(algorithmVc, 12, 100, 1);
|
---|
389 | ConfigureMutationRate(algorithmVc, 0.0, 1.0, 0.01);
|
---|
390 | //ConfigureMutationOperator(algorithmVc);
|
---|
391 | ConfigureElites(algorithmVc, 0, 10, 1);
|
---|
392 | //ConfigureSelectionOperator(algorithmVc, true);
|
---|
393 | return algorithmVc;
|
---|
394 | }
|
---|
395 |
|
---|
396 | private static void TestConfiguration(IValueConfiguration algorithmVc, GeneticAlgorithm baseLevelAlgorithm) {
|
---|
397 | IRandom rand = new FastRandom(0);
|
---|
398 | // set random values
|
---|
399 | for (int i = 0; i < 10; i++) {
|
---|
400 | IValueConfiguration clonedVc = (IValueConfiguration)algorithmVc.Clone();
|
---|
401 | GeneticAlgorithm newAlg = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
|
---|
402 | clonedVc.Randomize(rand);
|
---|
403 | clonedVc.Parameterize(newAlg);
|
---|
404 | Console.WriteLine(string.Format("PopSize: original: {0}, randomized: {1}", baseLevelAlgorithm.PopulationSize, newAlg.PopulationSize));
|
---|
405 | Console.WriteLine(string.Format("MutRate: original: {0}, randomized: {1}", baseLevelAlgorithm.MutationProbability, newAlg.MutationProbability));
|
---|
406 | Console.WriteLine(string.Format("MutOp: original: {0}, randomized: {1}", baseLevelAlgorithm.Mutator, newAlg.Mutator));
|
---|
407 | Console.WriteLine(string.Format("SelOp: original: {0}, randomized: {1}", baseLevelAlgorithm.Selector, newAlg.Selector));
|
---|
408 | //Console.WriteLine(string.Format("GrSi: original: {0}, randomized: {1}", "?", ((TournamentSelector)newAlg.Selector).GroupSizeParameter.Value));
|
---|
409 | Console.WriteLine("---");
|
---|
410 | }
|
---|
411 |
|
---|
412 | Console.WriteLine("=======================");
|
---|
413 | algorithmVc.Randomize(rand);
|
---|
414 | algorithmVc.Parameterize(baseLevelAlgorithm);
|
---|
415 | // mutate
|
---|
416 | for (int i = 0; i < 10; i++) {
|
---|
417 | IValueConfiguration clonedVc = (IValueConfiguration)algorithmVc.Clone();
|
---|
418 | GeneticAlgorithm newAlg = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
|
---|
419 | //clonedVc.Mutate(rand);
|
---|
420 |
|
---|
421 | //.Apply(rand, clonedVc); todo
|
---|
422 | clonedVc.Parameterize(newAlg);
|
---|
423 | Console.WriteLine(string.Format("PopSize: original: {0}, mutated: {1}", baseLevelAlgorithm.PopulationSize, newAlg.PopulationSize));
|
---|
424 | Console.WriteLine(string.Format("MutRate: original: {0}, mutated: {1}", baseLevelAlgorithm.MutationProbability, newAlg.MutationProbability));
|
---|
425 | Console.WriteLine(string.Format("MutOp: original: {0}, mutated: {1}", baseLevelAlgorithm.Mutator, newAlg.Mutator));
|
---|
426 | Console.WriteLine(string.Format("SelOp: original: {0}, mutated: {1}", baseLevelAlgorithm.Selector, newAlg.Selector));
|
---|
427 | //Console.WriteLine(string.Format("GrSi: original: {0}, mutated: {1}", ((TournamentSelector)baseLevelAlgorithm.Selector).GroupSizeParameter.Value, ((TournamentSelector)newAlg.Selector).GroupSizeParameter.Value));
|
---|
428 | Console.WriteLine("---");
|
---|
429 | }
|
---|
430 |
|
---|
431 | Console.WriteLine("=======================");
|
---|
432 | // cross
|
---|
433 | for (int i = 0; i < 10; i++) {
|
---|
434 | IValueConfiguration clonedVc1 = (IValueConfiguration)algorithmVc.Clone();
|
---|
435 | IValueConfiguration clonedVc2 = (IValueConfiguration)algorithmVc.Clone();
|
---|
436 |
|
---|
437 | GeneticAlgorithm first = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
|
---|
438 | GeneticAlgorithm second = (GeneticAlgorithm)baseLevelAlgorithm.Clone();
|
---|
439 |
|
---|
440 | clonedVc1.Randomize(rand);
|
---|
441 | clonedVc1.Parameterize(first);
|
---|
442 |
|
---|
443 | clonedVc2.Randomize(rand);
|
---|
444 | clonedVc2.Parameterize(second);
|
---|
445 |
|
---|
446 | var popSizeBefore = first.PopulationSize.Value;
|
---|
447 | var mutRateBefore = first.MutationProbability.Value;
|
---|
448 | var mutOpBefore = first.Mutator;
|
---|
449 | var selOpBefore = first.Selector;
|
---|
450 | //var groupSizeBefore = ((TournamentSelector)first.Selector).GroupSizeParameter.Value.Value;
|
---|
451 |
|
---|
452 | //clonedVc1.Cross(clonedVc2, rand); todo
|
---|
453 | clonedVc1.Parameterize(first);
|
---|
454 |
|
---|
455 | Console.WriteLine(string.Format("PopSize: first: {0}, second: {1}, crossed: {2}", popSizeBefore, second.PopulationSize, first.PopulationSize));
|
---|
456 | Console.WriteLine(string.Format("MutRate: first: {0}, second: {1}, crossed: {2}", mutRateBefore, second.MutationProbability, first.MutationProbability));
|
---|
457 | Console.WriteLine(string.Format("MutOp: first: {0}, second: {1}, crossed: {2}", mutOpBefore, second.Mutator, first.Mutator));
|
---|
458 | Console.WriteLine(string.Format("SelOp: first: {0}, second: {1}, crossed: {2}", selOpBefore, second.Selector, first.Selector));
|
---|
459 | //Console.WriteLine(string.Format("GrSi: first: {0}, second: {1}, crossed: {2}", groupSizeBefore, ((TournamentSelector)second.Selector).GroupSizeParameter.Value, ((TournamentSelector)first.Selector).GroupSizeParameter.Value));
|
---|
460 | Console.WriteLine("---");
|
---|
461 | }
|
---|
462 | Console.WriteLine("=======================");
|
---|
463 | }
|
---|
464 |
|
---|
465 | private static void ConfigureMutationOperator(IValueConfiguration algorithmVc) {
|
---|
466 | var mutationOperator = algorithmVc.ParameterConfigurations.Where(x => x.Name == "Mutator").SingleOrDefault();
|
---|
467 | mutationOperator.Optimize = true;
|
---|
468 |
|
---|
469 | // uncheck multiMutator to avoid Michalewicz issue
|
---|
470 | var multiMutator = mutationOperator.ValueConfigurations.Where(x => x.ActualValue.Value != null && x.ActualValue.Value.ItemName.StartsWith("Multi")).SingleOrDefault();
|
---|
471 | if (multiMutator != null) {
|
---|
472 | mutationOperator.ValueConfigurations.SetItemCheckedState(multiMutator, false);
|
---|
473 | }
|
---|
474 | }
|
---|
475 |
|
---|
476 | private static void ConfigureSelectionOperator(IValueConfiguration algorithmVc, bool configureTournamenSize) {
|
---|
477 | var selectionOperatorPc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "Selector").SingleOrDefault();
|
---|
478 | selectionOperatorPc.Optimize = true;
|
---|
479 |
|
---|
480 | foreach (var vc in selectionOperatorPc.ValueConfigurations) {
|
---|
481 | if (vc.ActualValue.ValueDataType == typeof(TournamentSelector)) {
|
---|
482 | selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
|
---|
483 | if (configureTournamenSize) {
|
---|
484 | vc.Optimize = true;
|
---|
485 | ConfigureTournamentGroupSize(vc);
|
---|
486 | }
|
---|
487 | } else if (vc.ActualValue.ValueDataType == typeof(RandomSelector)) {
|
---|
488 | selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
|
---|
489 | } else {
|
---|
490 | selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
|
---|
491 | }
|
---|
492 | }
|
---|
493 | }
|
---|
494 |
|
---|
495 | private static void ConfigureTournamentGroupSize(IValueConfiguration tournamentVc) {
|
---|
496 | var groupSizePc = tournamentVc.ParameterConfigurations.Where(x => x.ParameterName == "GroupSize").SingleOrDefault();
|
---|
497 | groupSizePc.Optimize = true;
|
---|
498 |
|
---|
499 | groupSizePc.ValueConfigurations.First().Optimize = true;
|
---|
500 | groupSizePc.ValueConfigurations.First().RangeConstraint.LowerBound = new IntValue(0);
|
---|
501 | groupSizePc.ValueConfigurations.First().RangeConstraint.UpperBound = new IntValue(10);
|
---|
502 | groupSizePc.ValueConfigurations.First().RangeConstraint.StepSize = new IntValue(1);
|
---|
503 | }
|
---|
504 |
|
---|
505 | private static void ConfigurePopulationSize(IValueConfiguration algorithmVc, int lower, int upper, int stepsize) {
|
---|
506 | var populationSizePc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "PopulationSize").SingleOrDefault();
|
---|
507 | populationSizePc.Optimize = true;
|
---|
508 | var populationSizeVc = populationSizePc.ValueConfigurations.First();
|
---|
509 | populationSizeVc.Optimize = true;
|
---|
510 | populationSizeVc.RangeConstraint.LowerBound = new IntValue(lower);
|
---|
511 | populationSizeVc.RangeConstraint.UpperBound = new IntValue(upper);
|
---|
512 | populationSizeVc.RangeConstraint.StepSize = new IntValue(stepsize);
|
---|
513 | }
|
---|
514 |
|
---|
515 | private static void ConfigureMutationRate(IValueConfiguration algorithmVc, double lower, double upper, double stepsize) {
|
---|
516 | var mutationRatePc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "MutationProbability").SingleOrDefault();
|
---|
517 | mutationRatePc.Optimize = true;
|
---|
518 | var mutationRateVc = mutationRatePc.ValueConfigurations.First();
|
---|
519 | mutationRateVc.Optimize = true;
|
---|
520 | mutationRateVc.RangeConstraint.LowerBound = new PercentValue(lower);
|
---|
521 | mutationRateVc.RangeConstraint.UpperBound = new PercentValue(upper);
|
---|
522 | mutationRateVc.RangeConstraint.StepSize = new PercentValue(stepsize);
|
---|
523 | }
|
---|
524 |
|
---|
525 | private static void ConfigureElites(IValueConfiguration algorithmVc, int from, int to, int stepSize) {
|
---|
526 | var elitesPc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "Elites").SingleOrDefault();
|
---|
527 | elitesPc.Optimize = true;
|
---|
528 | var elitesVc = elitesPc.ValueConfigurations.First();
|
---|
529 | elitesVc.Optimize = true;
|
---|
530 | elitesVc.RangeConstraint.LowerBound = new IntValue(from);
|
---|
531 | elitesVc.RangeConstraint.UpperBound = new IntValue(to);
|
---|
532 | elitesVc.RangeConstraint.StepSize = new IntValue(stepSize);
|
---|
533 | }
|
---|
534 |
|
---|
535 | private static void TestOptimization(EngineAlgorithm metaLevelAlgorithm) {
|
---|
536 | ContentManager.Initialize(new PersistenceContentManager());
|
---|
537 | string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Results");
|
---|
538 | if (!Directory.Exists(path))
|
---|
539 | Directory.CreateDirectory(path);
|
---|
540 | string id = DateTime.Now.ToString("yyyy.MM.dd - HH;mm;ss,ffff");
|
---|
541 | string resultPath = Path.Combine(path, string.Format("{0} - Result.hl", id));
|
---|
542 | string outputPath = Path.Combine(path, string.Format("{0} - Console.txt", id));
|
---|
543 |
|
---|
544 | using (var sw = new StreamWriter(outputPath)) {
|
---|
545 | sw.AutoFlush = true;
|
---|
546 |
|
---|
547 | StringBuilder sb1 = new StringBuilder();
|
---|
548 | sb1.AppendFormat("Meta.PopulationSize: {0}\n", metaAlgorithmPopulationSize);
|
---|
549 | sb1.AppendFormat("Meta.MaxGenerations: {0}\n", metaAlgorithmMaxGenerations);
|
---|
550 | sb1.AppendFormat("Meta.Repetitions : {0}\n", metaProblemRepetitions);
|
---|
551 | sb1.AppendFormat("Meta.MutProb : {0}\n", ((GeneticAlgorithm)metaLevelAlgorithm).MutationProbability.Value);
|
---|
552 | sb1.AppendFormat("Base.MaxGenerations: {0}\n", baseAlgorithmMaxGenerations);
|
---|
553 | sb1.AppendLine("Problems:");
|
---|
554 | foreach (var prob in ((MetaOptimizationProblem)metaLevelAlgorithm.Problem).Problems) {
|
---|
555 | sb1.Append(prob.Name);
|
---|
556 | var sotf = prob as SingleObjectiveTestFunctionProblem;
|
---|
557 | if (sotf != null) {
|
---|
558 | sb1.AppendFormat(" {0}", sotf.ProblemSize.Value);
|
---|
559 | }
|
---|
560 | sb1.AppendLine();
|
---|
561 | }
|
---|
562 | sw.WriteLine(sb1.ToString());
|
---|
563 | Console.WriteLine(sb1.ToString());
|
---|
564 | metaLevelAlgorithm.Stopped += new EventHandler(metaLevelAlgorithm_Stopped);
|
---|
565 | metaLevelAlgorithm.Paused += new EventHandler(metaLevelAlgorithm_Paused);
|
---|
566 | metaLevelAlgorithm.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(metaLevelAlgorithm_ExceptionOccurred);
|
---|
567 |
|
---|
568 | metaLevelAlgorithm.Start();
|
---|
569 | int i = 0;
|
---|
570 | int currentGeneration = -1;
|
---|
571 | do {
|
---|
572 | Thread.Sleep(500);
|
---|
573 | if (metaLevelAlgorithm.Results.ContainsKey("Generations") && ((IntValue)metaLevelAlgorithm.Results["Generations"].Value).Value != currentGeneration) {
|
---|
574 | while (metaLevelAlgorithm.Results.Count < 3) Thread.Sleep(100);
|
---|
575 | StringBuilder sb = new StringBuilder();
|
---|
576 | sb.AppendLine(DateTime.Now.ToLongTimeString());
|
---|
577 | sb.AppendLine("=================================");
|
---|
578 |
|
---|
579 | sb.AppendLine(metaLevelAlgorithm.ExecutionState.ToString());
|
---|
580 | var rsClone = (ResultCollection)metaLevelAlgorithm.Results.Clone();
|
---|
581 | foreach (var result in rsClone) {
|
---|
582 | sb.AppendLine(result.ToString());
|
---|
583 | if (result.Name == "Population") {
|
---|
584 | RunCollection rc = (RunCollection)result.Value;
|
---|
585 | var orderedRuns = rc.OrderBy(x => x.Results["AverageQualityNormalized"]);
|
---|
586 |
|
---|
587 | TableBuilder tb = new TableBuilder("QNorm", "PoSi", "MutRa", "Eli", "SelOp", "MutOp", "NrSelSubScopes");
|
---|
588 | foreach (IRun run in orderedRuns) {
|
---|
589 | string selector;
|
---|
590 | if (run.Parameters["Selector"] is TournamentSelector) {
|
---|
591 | selector = string.Format("{0} ({1})", run.Parameters["Selector"].ToString(), ((TournamentSelector)run.Parameters["Selector"]).GroupSizeParameter.Value.ToString());
|
---|
592 | } else {
|
---|
593 | selector = string.Format("{0}", run.Parameters["Selector"].ToString());
|
---|
594 | }
|
---|
595 |
|
---|
596 | tb.AppendRow(
|
---|
597 | ((DoubleValue)run.Results["AverageQualityNormalized"]).Value.ToString("#0.00"),
|
---|
598 | ((IntValue)run.Parameters["PopulationSize"]).Value.ToString(),
|
---|
599 | ((DoubleValue)run.Parameters["MutationProbability"]).Value.ToString("0.00"),
|
---|
600 | ((IntValue)run.Parameters["Elites"]).Value.ToString(),
|
---|
601 | Shorten(selector, 20),
|
---|
602 | Shorten(run.Parameters.ContainsKey("Mutator") ? run.Parameters["Mutator"].ToString() : "null", 40),
|
---|
603 | ((ISelector)run.Parameters["Selector"]).NumberOfSelectedSubScopesParameter.Value.ToString());
|
---|
604 | }
|
---|
605 | sb.AppendLine(tb.ToString());
|
---|
606 | }
|
---|
607 | } // foreach
|
---|
608 | //Console.Clear();
|
---|
609 | Console.WriteLine(sb.ToString());
|
---|
610 | sw.WriteLine(sb.ToString());
|
---|
611 | currentGeneration = ((IntValue)metaLevelAlgorithm.Results["Generations"].Value).Value;
|
---|
612 | } // if
|
---|
613 | //if (i % 30 == 0) GC.Collect();
|
---|
614 | i++;
|
---|
615 | } while (metaLevelAlgorithm.ExecutionState != ExecutionState.Stopped);
|
---|
616 | }
|
---|
617 |
|
---|
618 | Console.WriteLine();
|
---|
619 | Console.WriteLine("Storing...");
|
---|
620 |
|
---|
621 | ContentManager.Save((IStorableContent)metaLevelAlgorithm, resultPath, true);
|
---|
622 | Console.WriteLine("Finished");
|
---|
623 | }
|
---|
624 |
|
---|
625 | private static void metaLevelAlgorithm_ExceptionOccurred(object sender, EventArgs<Exception> e) {
|
---|
626 | Console.WriteLine("metaLevelAlgorithm_ExceptionOccurred");
|
---|
627 | Console.WriteLine(e.Value.ToString());
|
---|
628 | if (e.Value.InnerException != null) {
|
---|
629 | Console.WriteLine(e.Value.InnerException.ToString());
|
---|
630 | }
|
---|
631 | }
|
---|
632 |
|
---|
633 | private static void metaLevelAlgorithm_Paused(object sender, EventArgs e) {
|
---|
634 | Console.WriteLine("metaLevelAlgorithm_Paused");
|
---|
635 | }
|
---|
636 |
|
---|
637 | private static void metaLevelAlgorithm_Stopped(object sender, EventArgs e) {
|
---|
638 | Console.WriteLine("metaLevelAlgorithm_Stopped");
|
---|
639 | }
|
---|
640 |
|
---|
641 | private static void TestShorten() {
|
---|
642 | int n = 8;
|
---|
643 | Console.WriteLine(Shorten("1", n));
|
---|
644 | Console.WriteLine(Shorten("12", n));
|
---|
645 | Console.WriteLine(Shorten("123", n));
|
---|
646 | Console.WriteLine(Shorten("1234", n));
|
---|
647 | Console.WriteLine(Shorten("12345", n));
|
---|
648 | Console.WriteLine(Shorten("123456", n));
|
---|
649 | Console.WriteLine(Shorten("1234567", n));
|
---|
650 | Console.WriteLine(Shorten("12345678", n));
|
---|
651 | Console.WriteLine(Shorten("123456789", n));
|
---|
652 | Console.WriteLine(Shorten("1234567890", n));
|
---|
653 | Console.WriteLine(Shorten("12345678901", n));
|
---|
654 | }
|
---|
655 |
|
---|
656 | private static string Shorten(string s, int n) {
|
---|
657 | string placeholder = "..";
|
---|
658 | if (s.Length <= n) return s;
|
---|
659 | int len = n / 2 - placeholder.Length / 2;
|
---|
660 | string start = s.Substring(0, len);
|
---|
661 | string end = s.Substring(s.Length - len, len);
|
---|
662 | return start + placeholder + end;
|
---|
663 | }
|
---|
664 |
|
---|
665 | private static void TestIntSampling() {
|
---|
666 | System.Random rand = new System.Random();
|
---|
667 | int lower = 10;
|
---|
668 | int upper = 20;
|
---|
669 | int stepsize = 1;
|
---|
670 | for (int i = 0; i < 100; i++) {
|
---|
671 | int val;
|
---|
672 | do {
|
---|
673 | val = rand.Next(lower / stepsize, upper / stepsize + 1) * stepsize;
|
---|
674 | } while (val < lower || val > upper);
|
---|
675 | Console.WriteLine(val);
|
---|
676 | }
|
---|
677 | }
|
---|
678 |
|
---|
679 | private static void TestDoubleSampling() {
|
---|
680 | System.Random rand = new System.Random();
|
---|
681 | double lower = 2;
|
---|
682 | double upper = 3;
|
---|
683 | double stepsize = 0.6;
|
---|
684 | for (int i = 0; i < 100; i++) {
|
---|
685 | double val;
|
---|
686 | do {
|
---|
687 | val = Math.Round((rand.NextDouble() * (upper - lower) + lower) / stepsize, 0) * stepsize;
|
---|
688 | } while (val < lower || val > upper);
|
---|
689 | Console.WriteLine(val);
|
---|
690 | }
|
---|
691 | }
|
---|
692 |
|
---|
693 | private static IEnumerable<IItem> GetValidValues(IValueParameter valueParameter) {
|
---|
694 | return ApplicationManager.Manager.GetInstances(valueParameter.DataType).Select(x => (IItem)x).OrderBy(x => x.ItemName);
|
---|
695 | }
|
---|
696 | }
|
---|
697 |
|
---|
698 | public class Node {
|
---|
699 | public string Name { get; set; }
|
---|
700 | public int ActualValue { get; set; }
|
---|
701 | public int[] PossibleValues { get; set; }
|
---|
702 | public List<Node> ChildNodes { get; set; }
|
---|
703 |
|
---|
704 | public Node(string name) {
|
---|
705 | this.Name = name;
|
---|
706 | PossibleValues = new int[] { 1, 2, 3 };
|
---|
707 | ChildNodes = new List<Node>();
|
---|
708 | }
|
---|
709 |
|
---|
710 | public void Init() {
|
---|
711 | this.ActualValue = PossibleValues.First();
|
---|
712 | foreach (var child in ChildNodes) {
|
---|
713 | child.Init();
|
---|
714 | }
|
---|
715 | }
|
---|
716 |
|
---|
717 | public override string ToString() {
|
---|
718 | StringBuilder sb = new StringBuilder();
|
---|
719 | sb.Append(string.Format("{0}:{1}", this.Name, this.ActualValue));
|
---|
720 | if (this.ChildNodes.Count() > 0) {
|
---|
721 | sb.Append(" (");
|
---|
722 | var lst = new List<string>();
|
---|
723 | foreach (Node child in ChildNodes) {
|
---|
724 | lst.Add(child.ToString());
|
---|
725 | }
|
---|
726 | sb.Append(string.Join(", ", lst.ToArray()));
|
---|
727 | sb.Append(")");
|
---|
728 | }
|
---|
729 |
|
---|
730 | return sb.ToString();
|
---|
731 | }
|
---|
732 | }
|
---|
733 |
|
---|
734 | public class NodeEnumerator : IEnumerator<Node> {
|
---|
735 | private Node node;
|
---|
736 | private List<IEnumerator> enumerators;
|
---|
737 |
|
---|
738 | public NodeEnumerator(Node node) {
|
---|
739 | this.node = node;
|
---|
740 | this.enumerators = new List<IEnumerator>();
|
---|
741 | }
|
---|
742 |
|
---|
743 | public Node Current {
|
---|
744 | get { return node; }
|
---|
745 | }
|
---|
746 | object IEnumerator.Current {
|
---|
747 | get { return Current; }
|
---|
748 | }
|
---|
749 |
|
---|
750 | public void Dispose() { }
|
---|
751 |
|
---|
752 | public bool MoveNext() {
|
---|
753 | int i = 0;
|
---|
754 | bool ok = false;
|
---|
755 | while (!ok && i < enumerators.Count) {
|
---|
756 | if (enumerators[i].MoveNext()) {
|
---|
757 | ok = true;
|
---|
758 | } else {
|
---|
759 | i++;
|
---|
760 | }
|
---|
761 | }
|
---|
762 |
|
---|
763 | if (ok) {
|
---|
764 | for (int k = i - 1; k >= 0; k--) {
|
---|
765 | enumerators[k].Reset();
|
---|
766 | enumerators[k].MoveNext();
|
---|
767 | }
|
---|
768 | } else {
|
---|
769 | return false;
|
---|
770 | }
|
---|
771 |
|
---|
772 | node.ActualValue = (int)enumerators[0].Current;
|
---|
773 | return true;
|
---|
774 | }
|
---|
775 |
|
---|
776 | public void Reset() {
|
---|
777 | enumerators.Clear();
|
---|
778 | enumerators.Add(node.PossibleValues.GetEnumerator());
|
---|
779 | enumerators[0].Reset();
|
---|
780 |
|
---|
781 | foreach (var child in node.ChildNodes) {
|
---|
782 | var enumerator = new NodeEnumerator(child);
|
---|
783 | enumerator.Reset();
|
---|
784 | enumerator.MoveNext();
|
---|
785 | enumerators.Add(enumerator);
|
---|
786 | }
|
---|
787 | }
|
---|
788 | }
|
---|
789 | }
|
---|