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