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