1 | using System.Collections.Generic;
|
---|
2 | using System.Diagnostics;
|
---|
3 | using System.Linq;
|
---|
4 | using HeuristicLab.Algorithms.GeneticAlgorithm;
|
---|
5 | using HeuristicLab.Core;
|
---|
6 | using HeuristicLab.PluginInfrastructure;
|
---|
7 | using HeuristicLab.Parameters;
|
---|
8 | using HeuristicLab.Problems.MetaOptimization;
|
---|
9 | using HeuristicLab.Data;
|
---|
10 | using System;
|
---|
11 | using System.Threading;
|
---|
12 | using HeuristicLab.Random;
|
---|
13 | using HeuristicLab.Optimization;
|
---|
14 | using HeuristicLab.Common;
|
---|
15 | using System.IO;
|
---|
16 | using HeuristicLab.Problems.TestFunctions;
|
---|
17 | using System.Text;
|
---|
18 | using HeuristicLab.Selection;
|
---|
19 |
|
---|
20 | namespace HeuristicLab.MetaOptimization.Test {
|
---|
21 | class Program {
|
---|
22 | private static int metaAlgorithmPopulationSize = 40;
|
---|
23 | private static int metaAlgorithmMaxGenerations = 30;
|
---|
24 |
|
---|
25 | private static int baseAlgorithmMaxGenerations = 100;
|
---|
26 |
|
---|
27 | static void Main(string[] args) {
|
---|
28 | //TestIntSampling();
|
---|
29 | //TestDoubleSampling();
|
---|
30 |
|
---|
31 | GeneticAlgorithm baseLevelAlgorithm = new GeneticAlgorithm();
|
---|
32 | MetaOptimizationProblem metaOptimizationProblem = new MetaOptimizationProblem();
|
---|
33 | GeneticAlgorithm metaLevelAlgorithm = GetMetaAlgorithm(metaOptimizationProblem);
|
---|
34 |
|
---|
35 | IValueConfiguration algorithmVc = SetupAlgorithm(baseLevelAlgorithm, metaOptimizationProblem);
|
---|
36 |
|
---|
37 | //Console.WriteLine("Press enter to start");
|
---|
38 | //Console.ReadLine();
|
---|
39 | //TestConfiguration(algorithmVc, baseLevelAlgorithm);
|
---|
40 |
|
---|
41 | //Console.WriteLine("Press enter to start");
|
---|
42 | //Console.ReadLine();
|
---|
43 | TestOptimization(metaLevelAlgorithm);
|
---|
44 |
|
---|
45 | //TestMemoryLeak(metaLevelAlgorithm);
|
---|
46 |
|
---|
47 | Console.ReadLine();
|
---|
48 | }
|
---|
49 |
|
---|
50 | private static void TestMemoryLeak(GeneticAlgorithm metaLevelAlgorithm) {
|
---|
51 | IValueConfiguration algorithmVc = ((MetaOptimizationProblem)metaLevelAlgorithm.Problem).AlgorithmParameterConfiguration;
|
---|
52 |
|
---|
53 | Console.WriteLine("Starting Memory Test...");
|
---|
54 | Console.ReadLine();
|
---|
55 |
|
---|
56 | var clones = new List<object>();
|
---|
57 | for (int i = 0; i < 1000; i++) {
|
---|
58 | var clone = algorithmVc.Clone();
|
---|
59 | clones.Add(clone);
|
---|
60 | }
|
---|
61 |
|
---|
62 | Console.WriteLine("Finished. Now GC...");
|
---|
63 | Console.ReadLine();
|
---|
64 |
|
---|
65 | GC.Collect();
|
---|
66 |
|
---|
67 | Console.WriteLine("Finished!");
|
---|
68 | Console.ReadLine();
|
---|
69 | }
|
---|
70 |
|
---|
71 | private static GeneticAlgorithm GetMetaAlgorithm(MetaOptimizationProblem metaOptimizationProblem) {
|
---|
72 | GeneticAlgorithm metaLevelAlgorithm = new GeneticAlgorithm();
|
---|
73 | metaLevelAlgorithm.PopulationSize.Value = metaAlgorithmPopulationSize;
|
---|
74 | metaLevelAlgorithm.MaximumGenerations.Value = metaAlgorithmMaxGenerations;
|
---|
75 |
|
---|
76 | metaLevelAlgorithm.Problem = metaOptimizationProblem;
|
---|
77 | metaLevelAlgorithm.Engine = new SequentialEngine.SequentialEngine();
|
---|
78 |
|
---|
79 | metaLevelAlgorithm.Mutator = new ParameterConfigurationManipulator();
|
---|
80 | metaLevelAlgorithm.MutationProbability.Value = 0.15;
|
---|
81 |
|
---|
82 | return metaLevelAlgorithm;
|
---|
83 | }
|
---|
84 |
|
---|
85 | private static IValueConfiguration SetupAlgorithm(GeneticAlgorithm baseLevelAlgorithm, MetaOptimizationProblem metaOptimizationProblem) {
|
---|
86 | baseLevelAlgorithm.Problem = new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem() {
|
---|
87 | Evaluator = new GriewankEvaluator(),
|
---|
88 | ProblemSize = new IntValue(1000)
|
---|
89 | };
|
---|
90 | baseLevelAlgorithm.MaximumGenerations.Value = baseAlgorithmMaxGenerations;
|
---|
91 |
|
---|
92 | metaOptimizationProblem.Algorithm = baseLevelAlgorithm;
|
---|
93 | IValueConfiguration algorithmVc = metaOptimizationProblem.AlgorithmParameterConfiguration;
|
---|
94 | metaOptimizationProblem.Problems.Add(new HeuristicLab.Problems.TestFunctions.SingleObjectiveTestFunctionProblem());
|
---|
95 |
|
---|
96 | ConfigurePopulationSize(algorithmVc);
|
---|
97 | ConfigureMutationRate(algorithmVc);
|
---|
98 | ConfigureMutationOperator(algorithmVc);
|
---|
99 | ConfigureElites(algorithmVc);
|
---|
100 | ConfigureSelectionOperator(algorithmVc);
|
---|
101 | return algorithmVc;
|
---|
102 | }
|
---|
103 |
|
---|
104 | private static void TestConfiguration(IValueConfiguration algorithmVc, GeneticAlgorithm baseLevelAlgorithm) {
|
---|
105 | IRandom rand = new FastRandom(0);
|
---|
106 | // set random values
|
---|
107 | for (int i = 0; i < 10; i++) {
|
---|
108 | IValueConfiguration clonedVc = (IValueConfiguration)algorithmVc.Clone();
|
---|
109 | clonedVc.Randomize(rand);
|
---|
110 | clonedVc.Parameterize((GeneticAlgorithm)clonedVc.ActualValue.Value);
|
---|
111 | GeneticAlgorithm newAlg = (GeneticAlgorithm)clonedVc.ActualValue.Value;
|
---|
112 | Console.WriteLine(string.Format("PopSize: original: {0}, randomized: {1}", baseLevelAlgorithm.PopulationSize, newAlg.PopulationSize));
|
---|
113 | Console.WriteLine(string.Format("MutRate: original: {0}, randomized: {1}", baseLevelAlgorithm.MutationProbability, newAlg.MutationProbability));
|
---|
114 | Console.WriteLine(string.Format("MutOp: original: {0}, randomized: {1}", baseLevelAlgorithm.Mutator, newAlg.Mutator));
|
---|
115 | Console.WriteLine(string.Format("SelOp: original: {0}, randomized: {1}", baseLevelAlgorithm.Selector, newAlg.Selector));
|
---|
116 | Console.WriteLine(string.Format("GrSi: original: {0}, randomized: {1}", "?", ((TournamentSelector)newAlg.Selector).GroupSizeParameter.Value));
|
---|
117 | Console.WriteLine("---");
|
---|
118 | }
|
---|
119 |
|
---|
120 | Console.WriteLine("=======================");
|
---|
121 | algorithmVc.Randomize(rand);
|
---|
122 | algorithmVc.Parameterize(baseLevelAlgorithm);
|
---|
123 | // mutate
|
---|
124 | for (int i = 0; i < 10; i++) {
|
---|
125 | IValueConfiguration clonedVc = (IValueConfiguration)algorithmVc.Clone();
|
---|
126 | clonedVc.Mutate(rand);
|
---|
127 | clonedVc.Parameterize((GeneticAlgorithm)clonedVc.ActualValue.Value);
|
---|
128 | GeneticAlgorithm newAlg = (GeneticAlgorithm)clonedVc.ActualValue.Value;
|
---|
129 | Console.WriteLine(string.Format("PopSize: original: {0}, mutated: {1}", baseLevelAlgorithm.PopulationSize, newAlg.PopulationSize));
|
---|
130 | Console.WriteLine(string.Format("MutRate: original: {0}, mutated: {1}", baseLevelAlgorithm.MutationProbability, newAlg.MutationProbability));
|
---|
131 | Console.WriteLine(string.Format("MutOp: original: {0}, mutated: {1}", baseLevelAlgorithm.Mutator, newAlg.Mutator));
|
---|
132 | Console.WriteLine(string.Format("SelOp: original: {0}, mutated: {1}", baseLevelAlgorithm.Selector, newAlg.Selector));
|
---|
133 | Console.WriteLine(string.Format("GrSi: original: {0}, mutated: {1}", ((TournamentSelector)baseLevelAlgorithm.Selector).GroupSizeParameter.Value, ((TournamentSelector)newAlg.Selector).GroupSizeParameter.Value));
|
---|
134 | Console.WriteLine("---");
|
---|
135 | }
|
---|
136 |
|
---|
137 | Console.WriteLine("=======================");
|
---|
138 | // cross
|
---|
139 | for (int i = 0; i < 10; i++) {
|
---|
140 | IValueConfiguration clonedVc1 = (IValueConfiguration)algorithmVc.Clone();
|
---|
141 | IValueConfiguration clonedVc2 = (IValueConfiguration)algorithmVc.Clone();
|
---|
142 |
|
---|
143 | GeneticAlgorithm first = (GeneticAlgorithm)clonedVc1.ActualValue.Value.Clone();
|
---|
144 | GeneticAlgorithm second = (GeneticAlgorithm)clonedVc2.ActualValue.Value.Clone();
|
---|
145 |
|
---|
146 | clonedVc1.Randomize(rand);
|
---|
147 | clonedVc1.Parameterize(first);
|
---|
148 |
|
---|
149 | clonedVc2.Randomize(rand);
|
---|
150 | clonedVc2.Parameterize(second);
|
---|
151 |
|
---|
152 | var popSizeBefore = first.PopulationSize.Value;
|
---|
153 | var mutRateBefore = first.MutationProbability.Value;
|
---|
154 | var mutOpBefore = first.Mutator;
|
---|
155 | var selOpBefore = first.Selector;
|
---|
156 | var groupSizeBefore = ((TournamentSelector)first.Selector).GroupSizeParameter.Value.Value;
|
---|
157 |
|
---|
158 | clonedVc1.Cross(clonedVc2, rand);
|
---|
159 | clonedVc1.Parameterize(first);
|
---|
160 |
|
---|
161 | Console.WriteLine(string.Format("PopSize: first: {0}, second: {1}, crossed: {2}", popSizeBefore, second.PopulationSize, first.PopulationSize));
|
---|
162 | Console.WriteLine(string.Format("MutRate: first: {0}, second: {1}, crossed: {2}", mutRateBefore, second.MutationProbability, first.MutationProbability));
|
---|
163 | Console.WriteLine(string.Format("MutOp: first: {0}, second: {1}, crossed: {2}", mutOpBefore, second.Mutator, first.Mutator));
|
---|
164 | Console.WriteLine(string.Format("SelOp: first: {0}, second: {1}, crossed: {2}", selOpBefore, second.Selector, first.Selector));
|
---|
165 | Console.WriteLine(string.Format("GrSi: first: {0}, second: {1}, crossed: {2}", groupSizeBefore, ((TournamentSelector)second.Selector).GroupSizeParameter.Value, ((TournamentSelector)first.Selector).GroupSizeParameter.Value));
|
---|
166 | Console.WriteLine("---");
|
---|
167 | }
|
---|
168 | Console.WriteLine("=======================");
|
---|
169 | }
|
---|
170 |
|
---|
171 | private static void ConfigureMutationOperator(IValueConfiguration algorithmVc) {
|
---|
172 | var mutationOperator = algorithmVc.ParameterConfigurations.Where(x => x.Name == "Mutator").SingleOrDefault();
|
---|
173 | mutationOperator.Optimize = true;
|
---|
174 |
|
---|
175 | // uncheck multiMutator to avoid Michalewicz issue
|
---|
176 | var multiMutator = mutationOperator.ValueConfigurations.Where(x => x.ActualValue.Value.ItemName.StartsWith("Multi")).SingleOrDefault();
|
---|
177 | if (multiMutator != null) {
|
---|
178 | mutationOperator.ValueConfigurations.SetItemCheckedState(multiMutator, false);
|
---|
179 | }
|
---|
180 | }
|
---|
181 |
|
---|
182 | private static void ConfigureSelectionOperator(IValueConfiguration algorithmVc) {
|
---|
183 | var selectionOperatorPc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "Selector").SingleOrDefault();
|
---|
184 | selectionOperatorPc.Optimize = true;
|
---|
185 |
|
---|
186 | foreach (var vc in selectionOperatorPc.ValueConfigurations) {
|
---|
187 | if (vc.ActualValue.ValueDataType == typeof(TournamentSelector)) {
|
---|
188 | selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, true);
|
---|
189 | vc.Optimize = true;
|
---|
190 | ConfigureTournamentGroupSize(vc);
|
---|
191 | } else {
|
---|
192 | selectionOperatorPc.ValueConfigurations.SetItemCheckedState(vc, false);
|
---|
193 | }
|
---|
194 | }
|
---|
195 | }
|
---|
196 |
|
---|
197 | private static void ConfigureTournamentGroupSize(IValueConfiguration tournamentVc) {
|
---|
198 | var groupSizePc = tournamentVc.ParameterConfigurations.Where(x => x.ParameterName == "GroupSize").SingleOrDefault();
|
---|
199 | groupSizePc.Optimize = true;
|
---|
200 |
|
---|
201 | groupSizePc.ValueConfigurations.First().Optimize = true;
|
---|
202 | groupSizePc.ValueConfigurations.First().RangeConstraint.LowerBound = new IntValue(0);
|
---|
203 | groupSizePc.ValueConfigurations.First().RangeConstraint.UpperBound = new IntValue(100);
|
---|
204 | groupSizePc.ValueConfigurations.First().RangeConstraint.StepSize = new IntValue(1);
|
---|
205 | }
|
---|
206 |
|
---|
207 | private static void ConfigurePopulationSize(IValueConfiguration algorithmVc) {
|
---|
208 | var populationSizePc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "PopulationSize").SingleOrDefault();
|
---|
209 | populationSizePc.Optimize = true;
|
---|
210 | var populationSizeVc = populationSizePc.ValueConfigurations.First();
|
---|
211 | populationSizeVc.Optimize = true;
|
---|
212 | populationSizeVc.RangeConstraint.LowerBound = new IntValue(20);
|
---|
213 | populationSizeVc.RangeConstraint.UpperBound = new IntValue(100);
|
---|
214 | populationSizeVc.RangeConstraint.StepSize = new IntValue(1);
|
---|
215 | }
|
---|
216 |
|
---|
217 | private static void ConfigureMutationRate(IValueConfiguration algorithmVc) {
|
---|
218 | var mutationRatePc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "MutationProbability").SingleOrDefault();
|
---|
219 | mutationRatePc.Optimize = true;
|
---|
220 | var mutationRateVc = mutationRatePc.ValueConfigurations.First();
|
---|
221 | mutationRateVc.Optimize = true;
|
---|
222 | mutationRateVc.RangeConstraint.LowerBound = new PercentValue(0.0);
|
---|
223 | mutationRateVc.RangeConstraint.UpperBound = new PercentValue(1.0);
|
---|
224 | mutationRateVc.RangeConstraint.StepSize = new PercentValue(0.01);
|
---|
225 | }
|
---|
226 |
|
---|
227 | private static void ConfigureElites(IValueConfiguration algorithmVc) {
|
---|
228 | var elitesPc = algorithmVc.ParameterConfigurations.Where(x => x.Name == "Elites").SingleOrDefault();
|
---|
229 | elitesPc.Optimize = true;
|
---|
230 | var elitesVc = elitesPc.ValueConfigurations.First();
|
---|
231 | elitesVc.Optimize = true;
|
---|
232 | elitesVc.RangeConstraint.LowerBound = new IntValue(0);
|
---|
233 | elitesVc.RangeConstraint.UpperBound = new IntValue(20);
|
---|
234 | elitesVc.RangeConstraint.StepSize = new IntValue(1);
|
---|
235 | }
|
---|
236 |
|
---|
237 | private static void TestOptimization(GeneticAlgorithm metaLevelAlgorithm) {
|
---|
238 | ContentManager.Initialize(new PersistenceContentManager());
|
---|
239 | string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Results");
|
---|
240 | if(!Directory.Exists(path))
|
---|
241 | Directory.CreateDirectory(path);
|
---|
242 | string id = DateTime.Now.ToString("MM.dd.yy - HH;mm;ss,ffff");
|
---|
243 | string resultPath = Path.Combine(path, string.Format("Test - {0} - Result.hl", id));
|
---|
244 | string outputPath = Path.Combine(path, string.Format("Test - {0} - Console.txt", id));
|
---|
245 |
|
---|
246 | using (var sw = new StreamWriter(outputPath)) {
|
---|
247 | metaLevelAlgorithm.Start();
|
---|
248 | int i = 0;
|
---|
249 | int currentGeneration = -1;
|
---|
250 | do {
|
---|
251 | Thread.Sleep(500);
|
---|
252 | try {
|
---|
253 | if (metaLevelAlgorithm.Results.ContainsKey("Generations") && ((IntValue)metaLevelAlgorithm.Results["Generations"].Value).Value != currentGeneration) {
|
---|
254 | StringBuilder sb = new StringBuilder();
|
---|
255 | sb.AppendLine(DateTime.Now.ToLongTimeString());
|
---|
256 | sb.AppendLine("=================================");
|
---|
257 |
|
---|
258 | foreach (var result in metaLevelAlgorithm.Results) {
|
---|
259 | sb.AppendLine(result.ToString());
|
---|
260 | if (result.Name == "Population") {
|
---|
261 | RunCollection rc = (RunCollection)result.Value;
|
---|
262 | var orderedRuns = rc.OrderBy(x => x.Results["BestQuality"]);
|
---|
263 |
|
---|
264 | sb.AppendLine("Qality PoSi MutRa Eli GrSi MutOp");
|
---|
265 | foreach (IRun run in orderedRuns) {
|
---|
266 | sb.AppendLine(string.Format("{0} {1} {2} {3} {4} {5}",
|
---|
267 | ((DoubleValue)run.Results["BestQuality"]).Value.ToString("#0.00").PadLeft(7, ' '),
|
---|
268 | ((IntValue)run.Parameters["PopulationSize"]).Value.ToString().PadLeft(3, ' ').PadRight(3, ' '),
|
---|
269 | ((DoubleValue)run.Parameters["MutationProbability"]).Value.ToString("0.00").PadLeft(5, ' '),
|
---|
270 | ((IntValue)run.Parameters["Elites"]).Value.ToString().PadLeft(3, ' '),
|
---|
271 | ((TournamentSelector)run.Parameters["Selector"]).GroupSizeParameter.Value.ToString().PadLeft(4, ' '),
|
---|
272 | run.Parameters["Mutator"]));
|
---|
273 | }
|
---|
274 | }
|
---|
275 | } // foreach
|
---|
276 | Console.Clear();
|
---|
277 | Console.WriteLine(sb.ToString());
|
---|
278 | sw.WriteLine(sb.ToString());
|
---|
279 | sw.Flush();
|
---|
280 | currentGeneration = ((IntValue)metaLevelAlgorithm.Results["Generations"].Value).Value;
|
---|
281 | } // if
|
---|
282 | if (i % 30 == 0) GC.Collect();
|
---|
283 | i++;
|
---|
284 | }
|
---|
285 | catch { }
|
---|
286 | } while (metaLevelAlgorithm.ExecutionState != ExecutionState.Stopped);
|
---|
287 | }
|
---|
288 |
|
---|
289 | Console.WriteLine();
|
---|
290 | Console.WriteLine("Storing...");
|
---|
291 |
|
---|
292 | ContentManager.Save(metaLevelAlgorithm, resultPath, true);
|
---|
293 | Console.WriteLine("Finished");
|
---|
294 | }
|
---|
295 |
|
---|
296 | private static void TestIntSampling() {
|
---|
297 | System.Random rand = new System.Random();
|
---|
298 | int lower = 10;
|
---|
299 | int upper = 20;
|
---|
300 | int stepsize = 7;
|
---|
301 | for (int i = 0; i < 100; i++) {
|
---|
302 | int val;
|
---|
303 | do {
|
---|
304 | val = rand.Next(lower / stepsize, upper / stepsize + 1) * stepsize;
|
---|
305 | } while (val < lower || val > upper);
|
---|
306 | Console.WriteLine(val);
|
---|
307 | }
|
---|
308 | }
|
---|
309 |
|
---|
310 | private static void TestDoubleSampling() {
|
---|
311 | System.Random rand = new System.Random();
|
---|
312 | double lower = 2;
|
---|
313 | double upper = 3;
|
---|
314 | double stepsize = 0.6;
|
---|
315 | for (int i = 0; i < 100; i++) {
|
---|
316 | double val;
|
---|
317 | do {
|
---|
318 | val = Math.Round((rand.NextDouble() * (upper - lower) + lower) / stepsize, 0) * stepsize;
|
---|
319 | } while (val < lower || val > upper);
|
---|
320 | Console.WriteLine(val);
|
---|
321 | }
|
---|
322 | }
|
---|
323 |
|
---|
324 | private static IEnumerable<IItem> GetValidValues(IValueParameter valueParameter) {
|
---|
325 | return ApplicationManager.Manager.GetInstances(valueParameter.DataType).Select(x => (IItem)x).OrderBy(x => x.ItemName);
|
---|
326 | }
|
---|
327 | }
|
---|
328 | }
|
---|