1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2019 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
4 | *
|
---|
5 | * This file is part of HeuristicLab.
|
---|
6 | *
|
---|
7 | * HeuristicLab is free software: you can redistribute it and/or modify
|
---|
8 | * it under the terms of the GNU General Public License as published by
|
---|
9 | * the Free Software Foundation, either version 3 of the License, or
|
---|
10 | * (at your option) any later version.
|
---|
11 | *
|
---|
12 | * HeuristicLab is distributed in the hope that it will be useful,
|
---|
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
15 | * GNU General Public License for more details.
|
---|
16 | *
|
---|
17 | * You should have received a copy of the GNU General Public License
|
---|
18 | * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
|
---|
19 | */
|
---|
20 | #endregion
|
---|
21 |
|
---|
22 | // 03/02/2020
|
---|
23 | // TODO LIST:
|
---|
24 | // 1. Dynamic reference point strategy
|
---|
25 | // 2. Normalized fitness value strategy, desibility function.
|
---|
26 | // 3. HVC calculation should be definitely improved, at least in the 2D case.
|
---|
27 | // 4. multiple point strategy when $\lambda>1$
|
---|
28 |
|
---|
29 | using HEAL.Attic;
|
---|
30 | using HeuristicLab.Analysis;
|
---|
31 | using HeuristicLab.Common;
|
---|
32 | using HeuristicLab.Core;
|
---|
33 | using HeuristicLab.Data;
|
---|
34 | using HeuristicLab.ExpressionGenerator;
|
---|
35 | using HeuristicLab.Optimization;
|
---|
36 | using HeuristicLab.Parameters;
|
---|
37 | using HeuristicLab.Problems.DataAnalysis;
|
---|
38 | using HeuristicLab.Problems.TestFunctions.MultiObjective;
|
---|
39 | using HeuristicLab.Random;
|
---|
40 | using System;
|
---|
41 | using System.Collections.Generic;
|
---|
42 | using System.Drawing;
|
---|
43 | using System.Linq;
|
---|
44 | using CancellationToken = System.Threading.CancellationToken;
|
---|
45 |
|
---|
46 | namespace HeuristicLab.Algorithms.DynamicALPS {
|
---|
47 | [Item("DynamicALPSAlgorithmBase", "Base class for all DynamicALPS algorithm variants.")]
|
---|
48 | [StorableType("C0141748-DF5A-4CA0-A3DD-1DFB98236F7E")]
|
---|
49 | public abstract class DynamicALPSAlgorithmBase : BasicAlgorithm {
|
---|
50 | #region data members
|
---|
51 |
|
---|
52 | [StorableType("75C9EA99-D699-4A1F-8AB2-AB86B7A2FD68")]
|
---|
53 | protected enum NeighborType { NEIGHBOR, POPULATION }
|
---|
54 |
|
---|
55 |
|
---|
56 | [StorableType("2A71E397-05CE-460F-B982-EE2F4B37C354")]
|
---|
57 | // TCHE = Chebyshev (Tchebyshev)
|
---|
58 | // PBI = Penalty-based boundary intersection
|
---|
59 | // AGG = Weighted sum
|
---|
60 | public enum FunctionType { TCHE, PBI, AGG }
|
---|
61 |
|
---|
62 | [Storable]
|
---|
63 | protected double[] IdealPoint { get; set; }
|
---|
64 | [Storable]
|
---|
65 | protected double[] NadirPoint { get; set; } // potentially useful for objective normalization
|
---|
66 |
|
---|
67 | [Storable]
|
---|
68 | protected double[][] lambda_moead;
|
---|
69 |
|
---|
70 | [Storable]
|
---|
71 | protected int[][] neighbourhood;
|
---|
72 |
|
---|
73 | [Storable]
|
---|
74 | protected IDynamicALPSSolution[] solutions;
|
---|
75 |
|
---|
76 | [Storable]
|
---|
77 | protected FunctionType functionType;
|
---|
78 |
|
---|
79 | [Storable]
|
---|
80 | protected IDynamicALPSSolution[] population;
|
---|
81 |
|
---|
82 | [Storable]
|
---|
83 | protected IDynamicALPSSolution[][] layerPopulation;
|
---|
84 |
|
---|
85 | [Storable]
|
---|
86 | protected bool[] activeLayer;
|
---|
87 |
|
---|
88 | [Storable]
|
---|
89 | protected double[] layerCrossoverProbability;
|
---|
90 |
|
---|
91 | [Storable]
|
---|
92 | protected IDynamicALPSSolution[][] layerDiscardPopulation;
|
---|
93 |
|
---|
94 | [Storable]
|
---|
95 | protected IDynamicALPSSolution[] layerDiscardIndivdual;
|
---|
96 |
|
---|
97 |
|
---|
98 | [Storable]
|
---|
99 | protected IDynamicALPSSolution[][] layerOffspringPopulation;
|
---|
100 |
|
---|
101 | [Storable]
|
---|
102 | protected IDynamicALPSSolution[][] layerJointPopulation;
|
---|
103 |
|
---|
104 | [Storable]
|
---|
105 | protected IDynamicALPSSolution[] offspringPopulation;
|
---|
106 |
|
---|
107 | //[Storable]
|
---|
108 | //protected IDynamicALPSSolution[] jointPopulation;
|
---|
109 |
|
---|
110 | [Storable]
|
---|
111 | protected int evaluatedSolutions;
|
---|
112 |
|
---|
113 | [Storable]
|
---|
114 | protected ExecutionContext executionContext;
|
---|
115 |
|
---|
116 | [Storable]
|
---|
117 | protected IScope globalScope;
|
---|
118 |
|
---|
119 | [Storable]
|
---|
120 | protected ExecutionState previousExecutionState;
|
---|
121 |
|
---|
122 | [Storable]
|
---|
123 | protected ExecutionState executionState;
|
---|
124 |
|
---|
125 | protected DoubleArray ReferencePoint {
|
---|
126 | get {
|
---|
127 | if (Problem is MultiObjectiveTestFunctionProblem) {
|
---|
128 | var problem = (MultiObjectiveTestFunctionProblem)Problem;
|
---|
129 | return problem.ReferencePoint;
|
---|
130 | }
|
---|
131 | else {
|
---|
132 | return null;
|
---|
133 | }
|
---|
134 | }
|
---|
135 | }
|
---|
136 | #endregion
|
---|
137 |
|
---|
138 | #region parameters
|
---|
139 | private const string SeedParameterName = "Seed";
|
---|
140 | private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
|
---|
141 | private const string PopulationSizeParameterName = "PopulationSize";
|
---|
142 | private const string ResultPopulationSizeParameterName = "ResultPopulationSize";
|
---|
143 | private const string CrossoverProbabilityParameterName = "CrossoverProbability";
|
---|
144 | private const string CrossoverParameterName = "Crossover";
|
---|
145 | private const string MutationProbabilityParameterName = "MutationProbability";
|
---|
146 | private const string MutatorParameterName = "Mutator";
|
---|
147 | private const string MaximumEvaluatedSolutionsParameterName = "MaximumEvaluatedSolutions";
|
---|
148 | private const string RandomParameterName = "Random";
|
---|
149 | private const string AnalyzerParameterName = "Analyzer";
|
---|
150 |
|
---|
151 |
|
---|
152 | // MOEA-D parameters
|
---|
153 | //private const string NeighbourSizeParameterName = "NeighbourSize";
|
---|
154 | //private const string NeighbourhoodSelectionProbabilityParameterName = "NeighbourhoodSelectionProbability";
|
---|
155 | //private const string MaximumNumberOfReplacedSolutionsParameterName = "MaximumNumberOfReplacedSolutions";
|
---|
156 | //private const string FunctionTypeParameterName = "FunctionType";
|
---|
157 | // private const string NormalizeObjectivesParameterName = "NormalizeObjectives";
|
---|
158 |
|
---|
159 | // SMS-EMOA parameters:
|
---|
160 | private const string LambdaParameterName = "Lambda"; // The number of offspring size
|
---|
161 | private const string ALPSLayersParameterName = "ALPSLayers"; // The number of offspring size
|
---|
162 | private const string ALPSAgeGapParameterName = "ALPSAgeGap"; // The number of offspring size
|
---|
163 | private const string InitializeLayerPopulationMethodName = "InitializationLayerPopulations";
|
---|
164 |
|
---|
165 |
|
---|
166 |
|
---|
167 | // "Parameters" are defined in "HeuristicLab.Parameters"
|
---|
168 | // Contains: generic parameters of every class/algorithm/instance,
|
---|
169 | // It seems that "I***ValueParameter" is declared in "Heuristic.core", where "***ValueParameter" are defined in "HeuristicLab.Parameter"
|
---|
170 | // The function of "I***ValueParameter" is to bridge current scripts to "HeuristicLab.Parameter".
|
---|
171 | public IValueParameter<MultiAnalyzer> AnalyzerParameter {
|
---|
172 | get { return (ValueParameter<MultiAnalyzer>)Parameters[AnalyzerParameterName]; }
|
---|
173 | }
|
---|
174 |
|
---|
175 | //public IConstrainedValueParameter<StringValue> FunctionTypeParameter
|
---|
176 | //{
|
---|
177 | // get { return (IConstrainedValueParameter<StringValue>)Parameters[FunctionTypeParameterName]; }
|
---|
178 | //}
|
---|
179 | //public IFixedValueParameter<IntValue> NeighbourSizeParameter
|
---|
180 | //{
|
---|
181 | // get { return (IFixedValueParameter<IntValue>)Parameters[NeighbourSizeParameterName]; }
|
---|
182 | //}
|
---|
183 | //public IFixedValueParameter<BoolValue> NormalizeObjectivesParameter
|
---|
184 | //{
|
---|
185 | // get { return (IFixedValueParameter<BoolValue>)Parameters[NormalizeObjectivesParameterName]; }
|
---|
186 | //}
|
---|
187 | //public IFixedValueParameter<IntValue> MaximumNumberOfReplacedSolutionsParameter
|
---|
188 | //{
|
---|
189 | // get { return (IFixedValueParameter<IntValue>)Parameters[MaximumNumberOfReplacedSolutionsParameterName]; }
|
---|
190 | //}
|
---|
191 | //public IFixedValueParameter<DoubleValue> NeighbourhoodSelectionProbabilityParameter
|
---|
192 | //{
|
---|
193 | // get { return (IFixedValueParameter<DoubleValue>)Parameters[NeighbourhoodSelectionProbabilityParameterName]; }
|
---|
194 | //}
|
---|
195 | public IFixedValueParameter<IntValue> SeedParameter {
|
---|
196 | get { return (IFixedValueParameter<IntValue>)Parameters[SeedParameterName]; }
|
---|
197 | }
|
---|
198 | public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
|
---|
199 | get { return (IFixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyParameterName]; }
|
---|
200 | }
|
---|
201 | private IValueParameter<IntValue> PopulationSizeParameter {
|
---|
202 | get { return (IValueParameter<IntValue>)Parameters[PopulationSizeParameterName]; }
|
---|
203 | }
|
---|
204 | // KF, SMS-EMOA
|
---|
205 | private IValueParameter<IntValue> LambdaParameter {
|
---|
206 | get { return (IValueParameter<IntValue>)Parameters[LambdaParameterName]; }
|
---|
207 | }
|
---|
208 | //// KF, DynamicALPS
|
---|
209 | private IValueParameter<IntValue> ALPSLayersParameter{
|
---|
210 | get { return (IValueParameter<IntValue>)Parameters[ALPSLayersParameterName]; }
|
---|
211 | }
|
---|
212 | private IValueParameter<IntValue> ALPSAgeGapParameter {
|
---|
213 | get { return (IValueParameter<IntValue>)Parameters[ALPSAgeGapParameterName]; }
|
---|
214 | }
|
---|
215 |
|
---|
216 | private IValueParameter<BoolValue> ALPSInitialzeLayerPopulationParameter {
|
---|
217 | get { return (IValueParameter<BoolValue>)Parameters[InitializeLayerPopulationMethodName]; }
|
---|
218 | }
|
---|
219 |
|
---|
220 |
|
---|
221 | private IValueParameter<IntValue> ResultPopulationSizeParameter {
|
---|
222 | get { return (IValueParameter<IntValue>)Parameters[ResultPopulationSizeParameterName]; }
|
---|
223 | }
|
---|
224 |
|
---|
225 | public IValueParameter<PercentValue> CrossoverProbabilityParameter {
|
---|
226 | get { return (IValueParameter<PercentValue>)Parameters[CrossoverProbabilityParameterName]; }
|
---|
227 | }
|
---|
228 | public IConstrainedValueParameter<ICrossover> CrossoverParameter {
|
---|
229 | get { return (IConstrainedValueParameter<ICrossover>)Parameters[CrossoverParameterName]; }
|
---|
230 | }
|
---|
231 | public IValueParameter<PercentValue> MutationProbabilityParameter {
|
---|
232 | get { return (IValueParameter<PercentValue>)Parameters[MutationProbabilityParameterName]; }
|
---|
233 | }
|
---|
234 | public IConstrainedValueParameter<IManipulator> MutatorParameter {
|
---|
235 | get { return (IConstrainedValueParameter<IManipulator>)Parameters[MutatorParameterName]; }
|
---|
236 | }
|
---|
237 | public IValueParameter<IntValue> MaximumEvaluatedSolutionsParameter {
|
---|
238 | get { return (IValueParameter<IntValue>)Parameters[MaximumEvaluatedSolutionsParameterName]; }
|
---|
239 | }
|
---|
240 | public IValueParameter<IRandom> RandomParameter {
|
---|
241 | get { return (IValueParameter<IRandom>)Parameters[RandomParameterName]; }
|
---|
242 | }
|
---|
243 | #endregion
|
---|
244 |
|
---|
245 | #region parameter properties
|
---|
246 | public new IMultiObjectiveHeuristicOptimizationProblem Problem {
|
---|
247 | get { return (IMultiObjectiveHeuristicOptimizationProblem)base.Problem; }
|
---|
248 | set { base.Problem = value; }
|
---|
249 | }
|
---|
250 | public int Seed {
|
---|
251 | get { return SeedParameter.Value.Value; }
|
---|
252 | set { SeedParameter.Value.Value = value; }
|
---|
253 | }
|
---|
254 | public bool SetSeedRandomly {
|
---|
255 | get { return SetSeedRandomlyParameter.Value.Value; }
|
---|
256 | set { SetSeedRandomlyParameter.Value.Value = value; }
|
---|
257 | }
|
---|
258 | public IntValue PopulationSize {
|
---|
259 | get { return PopulationSizeParameter.Value; }
|
---|
260 | set { PopulationSizeParameter.Value = value; }
|
---|
261 | }
|
---|
262 | public IntValue Lambda {
|
---|
263 | get { return LambdaParameter.Value; }
|
---|
264 | set { LambdaParameter.Value = value; }
|
---|
265 | }
|
---|
266 |
|
---|
267 | public IntValue ResultPopulationSize {
|
---|
268 | get { return ResultPopulationSizeParameter.Value; }
|
---|
269 | set { ResultPopulationSizeParameter.Value = value; }
|
---|
270 | }
|
---|
271 |
|
---|
272 | public IntValue ALPSLayers {
|
---|
273 | get { return ALPSLayersParameter.Value; }
|
---|
274 | set { ALPSLayersParameter.Value = value; }
|
---|
275 | }
|
---|
276 |
|
---|
277 | public IntValue ALPSAgeGap {
|
---|
278 | get { return ALPSAgeGapParameter.Value; }
|
---|
279 | set { ALPSAgeGapParameter.Value = value; }
|
---|
280 | }
|
---|
281 | public BoolValue UseAverageAge {
|
---|
282 | get { return ALPSInitialzeLayerPopulationParameter.Value; }
|
---|
283 | set { ALPSInitialzeLayerPopulationParameter.Value = value; }
|
---|
284 | }
|
---|
285 |
|
---|
286 | public PercentValue CrossoverProbability {
|
---|
287 | get { return CrossoverProbabilityParameter.Value; }
|
---|
288 | set { CrossoverProbabilityParameter.Value = value; }
|
---|
289 | }
|
---|
290 | public ICrossover Crossover {
|
---|
291 | get { return CrossoverParameter.Value; }
|
---|
292 | set { CrossoverParameter.Value = value; }
|
---|
293 | }
|
---|
294 | public PercentValue MutationProbability {
|
---|
295 | get { return MutationProbabilityParameter.Value; }
|
---|
296 | set { MutationProbabilityParameter.Value = value; }
|
---|
297 | }
|
---|
298 | public IManipulator Mutator {
|
---|
299 | get { return MutatorParameter.Value; }
|
---|
300 | set { MutatorParameter.Value = value; }
|
---|
301 | }
|
---|
302 | public MultiAnalyzer Analyzer {
|
---|
303 | get { return AnalyzerParameter.Value; }
|
---|
304 | set { AnalyzerParameter.Value = value; }
|
---|
305 | }
|
---|
306 | public IntValue MaximumEvaluatedSolutions {
|
---|
307 | get { return MaximumEvaluatedSolutionsParameter.Value; }
|
---|
308 | set { MaximumEvaluatedSolutionsParameter.Value = value; }
|
---|
309 | }
|
---|
310 | #endregion
|
---|
311 |
|
---|
312 | #region constructors
|
---|
313 | public DynamicALPSAlgorithmBase() {
|
---|
314 | // Add or define or specify the parameters that may be use in SMS-EMOA.
|
---|
315 | // ***("Name", "Description", "Value")
|
---|
316 | // Name Type Description
|
---|
317 | // FixedValueParameter: ANY Not changed???
|
---|
318 | // ValueParameter: Changable??? What is the difference between "ValueParameter" and "FixedVlaueParameter"?????
|
---|
319 |
|
---|
320 |
|
---|
321 | // types:
|
---|
322 | // IntValue
|
---|
323 | // BoolValue
|
---|
324 | // DoubleValue
|
---|
325 | // PercentValue
|
---|
326 | // ICrossover:
|
---|
327 | // IManipulator:
|
---|
328 | // IRandom:
|
---|
329 | // MultiAnalyzer:
|
---|
330 | // ---------
|
---|
331 | Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
|
---|
332 | Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
|
---|
333 | Parameters.Add(new ValueParameter<IntValue>(PopulationSizeParameterName, "The size of the population of solutions.", new IntValue(100)));
|
---|
334 | Parameters.Add(new ValueParameter<IntValue>(ResultPopulationSizeParameterName, "The size of the population of solutions.", new IntValue(100)));
|
---|
335 | Parameters.Add(new ValueParameter<PercentValue>(CrossoverProbabilityParameterName, "The probability that the crossover operator is applied.", new PercentValue(0.9)));
|
---|
336 | Parameters.Add(new ConstrainedValueParameter<ICrossover>(CrossoverParameterName, "The operator used to cross solutions."));
|
---|
337 | Parameters.Add(new ValueParameter<PercentValue>(MutationProbabilityParameterName, "The probability that the mutation operator is applied on a solution.", new PercentValue(0.25)));
|
---|
338 | Parameters.Add(new ConstrainedValueParameter<IManipulator>(MutatorParameterName, "The operator used to mutate solutions."));
|
---|
339 | Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
|
---|
340 | Parameters.Add(new ValueParameter<IntValue>(MaximumEvaluatedSolutionsParameterName, "The maximum number of evaluated solutions (approximately).", new IntValue(100_000)));
|
---|
341 | Parameters.Add(new ValueParameter<IRandom>(RandomParameterName, new FastRandom()));
|
---|
342 | Parameters.Add(new ValueParameter<BoolValue>(InitializeLayerPopulationMethodName, "Whether use average age to initialize the layer population or not. If not, move the older individuals to layer populations", new BoolValue(true)));
|
---|
343 |
|
---|
344 | // SMS-EMOA, kf
|
---|
345 | Parameters.Add(new ValueParameter<IntValue>(LambdaParameterName, "The size of the offsprings. Now, it only works when lambda = 1", new IntValue(1)));
|
---|
346 | // DynamicALPS, KF
|
---|
347 | Parameters.Add(new ValueParameter<IntValue>(ALPSLayersParameterName, "Test, maximum = 1000, defualt is 1", new IntValue(10)));
|
---|
348 | Parameters.Add(new ValueParameter<IntValue>(ALPSAgeGapParameterName, "Test, maximum = 1000, defualt is 20", new IntValue(20)));
|
---|
349 |
|
---|
350 |
|
---|
351 | }
|
---|
352 |
|
---|
353 | protected DynamicALPSAlgorithmBase(DynamicALPSAlgorithmBase original, Cloner cloner) : base(original, cloner) {
|
---|
354 | functionType = original.functionType;
|
---|
355 | evaluatedSolutions = original.evaluatedSolutions;
|
---|
356 | previousExecutionState = original.previousExecutionState;
|
---|
357 |
|
---|
358 | if (original.IdealPoint != null) {
|
---|
359 | IdealPoint = (double[])original.IdealPoint.Clone();
|
---|
360 | }
|
---|
361 |
|
---|
362 | if (original.NadirPoint != null) {
|
---|
363 | NadirPoint = (double[])original.NadirPoint.Clone();
|
---|
364 | }
|
---|
365 |
|
---|
366 | if (original.lambda_moead != null) {
|
---|
367 | lambda_moead = (double[][])original.lambda_moead.Clone();
|
---|
368 | }
|
---|
369 |
|
---|
370 | if (original.neighbourhood != null) {
|
---|
371 | neighbourhood = (int[][])original.neighbourhood.Clone();
|
---|
372 | }
|
---|
373 |
|
---|
374 | if (original.solutions != null) {
|
---|
375 | solutions = original.solutions.Select(cloner.Clone).ToArray();
|
---|
376 | }
|
---|
377 |
|
---|
378 | if (original.population != null) {
|
---|
379 | population = original.population.Select(cloner.Clone).ToArray();
|
---|
380 | }
|
---|
381 |
|
---|
382 | if (original.offspringPopulation != null) {
|
---|
383 | offspringPopulation = original.offspringPopulation.Select(cloner.Clone).ToArray();
|
---|
384 | }
|
---|
385 |
|
---|
386 | //if (original.jointPopulation != null) {
|
---|
387 | // jointPopulation = original.jointPopulation.Select(x => cloner.Clone(x)).ToArray();
|
---|
388 | //}
|
---|
389 |
|
---|
390 | if (original.executionContext != null) {
|
---|
391 | executionContext = cloner.Clone(original.executionContext);
|
---|
392 | }
|
---|
393 |
|
---|
394 | if (original.globalScope != null) {
|
---|
395 | globalScope = cloner.Clone(original.globalScope);
|
---|
396 | }
|
---|
397 | }
|
---|
398 |
|
---|
399 |
|
---|
400 |
|
---|
401 | [StorableConstructor]
|
---|
402 | protected DynamicALPSAlgorithmBase(StorableConstructorFlag deserializing) : base(deserializing) { }
|
---|
403 | #endregion
|
---|
404 |
|
---|
405 | private void InitializePopulation(ExecutionContext executionContext, CancellationToken cancellationToken, IRandom random, bool[] maximization) {
|
---|
406 | // creator: how to create the initilized population. "UniformRandom" is used here.
|
---|
407 | // TODO: LHS, latin hypercube sampling? Exisit???
|
---|
408 | var creator = Problem.SolutionCreator;
|
---|
409 | var evaluator = Problem.Evaluator;
|
---|
410 |
|
---|
411 | // dimensions: objective space
|
---|
412 | var dimensions = maximization.Length;
|
---|
413 | var populationSize = PopulationSize.Value;
|
---|
414 | population = new IDynamicALPSSolution[populationSize];
|
---|
415 |
|
---|
416 | var parentScope = executionContext.Scope;
|
---|
417 | // first, create all individuals
|
---|
418 | for (int i = 0; i < populationSize; ++i) {
|
---|
419 | var childScope = new Scope(i.ToString()) { Parent = parentScope };
|
---|
420 | ExecuteOperation(executionContext, cancellationToken, executionContext.CreateChildOperation(creator, childScope));
|
---|
421 | parentScope.SubScopes.Add(childScope);
|
---|
422 | }
|
---|
423 |
|
---|
424 | for (int i = 0; i < populationSize; ++i) {
|
---|
425 | var childScope = parentScope.SubScopes[i];
|
---|
426 | ExecuteOperation(executionContext, cancellationToken, executionContext.CreateChildOperation(evaluator, childScope));
|
---|
427 |
|
---|
428 | var qualities = (DoubleArray)childScope.Variables["Qualities"].Value;
|
---|
429 |
|
---|
430 | // solution: a method, contains a decision vector and objecitve values
|
---|
431 | // solution.Qualities: objective values, fitness values
|
---|
432 | // solution.Individual: decision vector
|
---|
433 | var solution = new DynamicALPSSolution(childScope, dimensions, 0);
|
---|
434 | for (int j = 0; j < dimensions; ++j) {
|
---|
435 | // TODO: convert maximization problems into minimization problems.
|
---|
436 | solution.Qualities[j] = maximization[j] ? 1 - qualities[j] : qualities[j];
|
---|
437 | }
|
---|
438 |
|
---|
439 | // population is a collection of solution.
|
---|
440 | population[i] = solution;
|
---|
441 |
|
---|
442 | // KF, DyanmicALPS
|
---|
443 | population[i].HypervolumeContribution[0] = -0;
|
---|
444 | population[i].NondominanceRanking[0] = -0;
|
---|
445 | population[i].Age = 1;
|
---|
446 | population[i].IndividualPc = CrossoverProbability.Value;
|
---|
447 | population[i].IndividualPc = MutationProbability.Value;
|
---|
448 | }
|
---|
449 | }
|
---|
450 |
|
---|
451 | protected void InitializeAlgorithm(CancellationToken cancellationToken) { // Type of random operator, "FastRandom" in this script.
|
---|
452 | // RandomParameter <-- Parameters in "HeuristicLab.Core.ParameterizedNameItem",
|
---|
453 | var rand = RandomParameter.Value;
|
---|
454 |
|
---|
455 | // Initialize random seed
|
---|
456 | // If random seed exist, get it; otherwise,
|
---|
457 | if (SetSeedRandomly) Seed = RandomSeedGenerator.GetSeed();
|
---|
458 |
|
---|
459 | // Call
|
---|
460 | rand.Reset(Seed);
|
---|
461 |
|
---|
462 | bool[] maximization = ((BoolArray)Problem.MaximizationParameter.ActualValue).CloneAsArray();
|
---|
463 |
|
---|
464 | // dimensions: the dimension in an objective space
|
---|
465 | var dimensions = maximization.Length;
|
---|
466 |
|
---|
467 |
|
---|
468 | var populationSize = PopulationSize.Value;
|
---|
469 |
|
---|
470 | InitializePopulation(executionContext, cancellationToken, rand, maximization);
|
---|
471 |
|
---|
472 | IdealPoint = new double[dimensions];
|
---|
473 | IdealPoint.UpdateIdeal(population);
|
---|
474 |
|
---|
475 | NadirPoint = Enumerable.Repeat(double.MinValue, dimensions).ToArray();
|
---|
476 | //NadirPoint = new double[dimensions];
|
---|
477 | NadirPoint.UpdateNadir(population);
|
---|
478 |
|
---|
479 |
|
---|
480 | evaluatedSolutions = populationSize;
|
---|
481 | }
|
---|
482 |
|
---|
483 | protected override void Initialize(CancellationToken cancellationToken) {
|
---|
484 | globalScope = new Scope("Global Scope");
|
---|
485 | executionContext = new ExecutionContext(null, this, globalScope);
|
---|
486 |
|
---|
487 | // set the execution context for parameters to allow lookup
|
---|
488 | foreach (var parameter in Problem.Parameters.OfType<IValueParameter>()) {
|
---|
489 | // we need all of these in order for the wiring of the operators to work
|
---|
490 | globalScope.Variables.Add(new Variable(parameter.Name, parameter.Value));
|
---|
491 | }
|
---|
492 | globalScope.Variables.Add(new Variable("Results", Results)); // make results available as a parameter for analyzers etc.
|
---|
493 |
|
---|
494 | base.Initialize(cancellationToken);
|
---|
495 | }
|
---|
496 |
|
---|
497 | public override bool SupportsPause => true;
|
---|
498 |
|
---|
499 |
|
---|
500 |
|
---|
501 |
|
---|
502 | // Mate Selection.
|
---|
503 | // Randomly select a specific number of individuals for later operators.
|
---|
504 | // Inputs:
|
---|
505 | // 1. random: Random number generate method
|
---|
506 | // 2. numberOfSolutionToSelect: The number of selection
|
---|
507 | // Outputs:
|
---|
508 | // 1. listOfSolutions: The selection individuals
|
---|
509 | protected List<int> MatingSelection(IRandom random, int numberOfSolutionsToSelect) {
|
---|
510 | int populationSize = PopulationSize.Value;
|
---|
511 |
|
---|
512 | var listOfSolutions = new List<int>(numberOfSolutionsToSelect);
|
---|
513 |
|
---|
514 | while (listOfSolutions.Count < numberOfSolutionsToSelect) {
|
---|
515 | var selectedSolution = random.Next(populationSize);
|
---|
516 |
|
---|
517 | bool flag = true;
|
---|
518 | foreach (int individualId in listOfSolutions) {
|
---|
519 | if (individualId == selectedSolution) {
|
---|
520 | flag = false;
|
---|
521 | break;
|
---|
522 | }
|
---|
523 | }
|
---|
524 |
|
---|
525 | if (flag) {
|
---|
526 | listOfSolutions.Add(selectedSolution);
|
---|
527 | }
|
---|
528 | }
|
---|
529 | return listOfSolutions;
|
---|
530 | }
|
---|
531 |
|
---|
532 | protected void ApplyCrossover(int lambda) {
|
---|
533 | }
|
---|
534 |
|
---|
535 | protected void ApplyMutation(int lambda) {
|
---|
536 | }
|
---|
537 |
|
---|
538 |
|
---|
539 | protected void ApplyEvaluation(int lambda) {
|
---|
540 | }
|
---|
541 |
|
---|
542 | protected void ApplyMateSelection(int rho) {
|
---|
543 | }
|
---|
544 |
|
---|
545 | protected void InitializeLayer(int indexLayer, int populationSize, int lambda) {
|
---|
546 | layerPopulation[indexLayer] = new IDynamicALPSSolution[populationSize];
|
---|
547 | layerJointPopulation[indexLayer] = new IDynamicALPSSolution[populationSize + lambda];
|
---|
548 | layerOffspringPopulation[indexLayer] = new IDynamicALPSSolution[lambda];
|
---|
549 | layerDiscardPopulation[indexLayer] = new IDynamicALPSSolution[populationSize];
|
---|
550 | activeLayer[indexLayer] = true;
|
---|
551 | }
|
---|
552 |
|
---|
553 |
|
---|
554 | // Select/Discard the individual(s) according to HVC
|
---|
555 | protected void SmetricSelection(int lambda, int nLayerALPS) {
|
---|
556 | var wholePopulation = layerJointPopulation[nLayerALPS];
|
---|
557 | var qualities = wholePopulation.Select(x => x.Qualities).ToArray();
|
---|
558 |
|
---|
559 | var maxPoint = Enumerable.Range(0, IdealPoint.Length).Select(idx => qualities.Max(q => q[idx])).ToArray();
|
---|
560 |
|
---|
561 | var maximization = Enumerable.Repeat(false, IdealPoint.Length).ToArray(); // Minimization or maximization ????
|
---|
562 | var pf2 = DominationCalculator<IDynamicALPSSolution>.CalculateAllParetoFronts(wholePopulation, qualities, maximization, out int[] ranking);
|
---|
563 |
|
---|
564 | int numberOfLayer; // number of layers in PF
|
---|
565 | int numberOfLastLayer; // number of discarded points in PF (the number of points in the last layer)
|
---|
566 |
|
---|
567 | pf2.RemoveAt(pf2.Count() - 1);
|
---|
568 | numberOfLayer = pf2.Count();
|
---|
569 | numberOfLastLayer = pf2[numberOfLayer - 1].Count();
|
---|
570 | double[] hvc = new double[numberOfLastLayer];
|
---|
571 | int discardIndex;
|
---|
572 | if (numberOfLastLayer > lambda) {
|
---|
573 | double tempHV;
|
---|
574 | double smetric;
|
---|
575 | var lastLayer = pf2.Last();
|
---|
576 |
|
---|
577 | // TODO: This can be use for dynamic reference point strategy later. Kaifeng , 02/2020
|
---|
578 | // smetric = Hypervolume.Calculate(lastLayer.Select(x => x.Item2), Enumerable.Repeat(11d, NadirPoint.Length).ToArray(), maximization);
|
---|
579 |
|
---|
580 | var reference = Enumerable.Repeat(double.MaxValue, maximization.Length).ToArray(); // TODO Dynamic Reference point for each layer. Maximum * 1.1
|
---|
581 | //if (nLayerALPS != 0) {
|
---|
582 | for (int i = 0; i < reference.Length; i++) {
|
---|
583 | reference[i] = 1.1 * maxPoint[i];
|
---|
584 | if (reference[i] > 10000) {
|
---|
585 | reference[i] = 9999; // set a upper bound for the reference point
|
---|
586 | }
|
---|
587 | }
|
---|
588 | //}
|
---|
589 | //else {
|
---|
590 | // reference = ReferencePoint.ToArray();
|
---|
591 | //}
|
---|
592 |
|
---|
593 | var nondominated = NonDominatedSelect.GetDominatingVectors(lastLayer.Select(x => x.Item2), reference, maximization, false);
|
---|
594 | smetric = nondominated.Any() ? Hypervolume.Calculate(nondominated, reference, maximization) : int.MinValue;
|
---|
595 |
|
---|
596 | for (int ii = 0; ii < lastLayer.Count; ++ii) {
|
---|
597 | try { // TODO: This can be use for dynamic reference point strategy later. Kaifeng , 02/2020
|
---|
598 | // tempHV = Hypervolume.Calculate(indices.Where(idx => idx != ii).Select(idx => lastLayer[idx].Item2), Enumerable.Repeat(11d, NadirPoint.Length).ToArray(), maximization);
|
---|
599 | tempHV = Hypervolume.Calculate(Enumerable.Range(0, lastLayer.Count).Where(idx => idx != ii).Select(idx => lastLayer[idx].Item2), reference, maximization);
|
---|
600 | }
|
---|
601 | catch {
|
---|
602 | tempHV = int.MinValue;
|
---|
603 | }
|
---|
604 | hvc[ii] = smetric - tempHV;
|
---|
605 | tempHV = 0;
|
---|
606 | }
|
---|
607 |
|
---|
608 | discardIndex = Array.IndexOf(hvc, hvc.Min());
|
---|
609 | //layerDiscardPopulation[nLayerALPS] = pf2[numberOfLayer - 1][discardIndex].Item1.ToArray();
|
---|
610 | layerDiscardIndivdual[nLayerALPS] = pf2[numberOfLayer - 1].Select(x => x.Item1).ToArray()[discardIndex];
|
---|
611 | pf2[numberOfLayer - 1].RemoveAt(discardIndex);
|
---|
612 | }
|
---|
613 | else {
|
---|
614 | // TODO: This should be updated when $lambda > 1$
|
---|
615 | discardIndex = pf2.Count() - 1;
|
---|
616 | layerDiscardIndivdual[nLayerALPS] = pf2[discardIndex].Select(x => x.Item1).ToArray()[0];
|
---|
617 | pf2.RemoveAt(pf2.Count() - 1);
|
---|
618 | numberOfLayer = numberOfLayer - 1;
|
---|
619 |
|
---|
620 | }
|
---|
621 | layerPopulation[nLayerALPS] = pf2.SelectMany(x => x.Select(y => y.Item1)).ToArray();
|
---|
622 |
|
---|
623 | }
|
---|
624 |
|
---|
625 | public static double SampleGaussian(IRandom random, double mean, double stddev) {
|
---|
626 | // The method requires sampling from a uniform random of (0,1]
|
---|
627 | // but Random.NextDouble() returns a sample of [0,1).
|
---|
628 | double x1 = 1 - random.NextDouble();
|
---|
629 | double x2 = 1 - random.NextDouble();
|
---|
630 |
|
---|
631 | double y1 = Math.Sqrt(-2.0 * Math.Log(x1)) * Math.Cos(2.0 * Math.PI * x2);
|
---|
632 | return y1 * stddev + mean;
|
---|
633 | }
|
---|
634 |
|
---|
635 | protected int SMSEMOA(int populationSize, int lambda, int counterLayerALPS) {
|
---|
636 | var innerToken = new CancellationToken();
|
---|
637 | bool[] maximization = ((BoolArray)Problem.MaximizationParameter.ActualValue).CloneAsArray();
|
---|
638 | var maximumEvaluatedSolutions = MaximumEvaluatedSolutions.Value;
|
---|
639 | var crossover = Crossover;
|
---|
640 | var crossoverProbability = layerCrossoverProbability[0];
|
---|
641 | var mutator = Mutator;
|
---|
642 | var mutationProbability = MutationProbability.Value;
|
---|
643 | var evaluator = Problem.Evaluator;
|
---|
644 | var analyzer = Analyzer;
|
---|
645 | var rand = RandomParameter.Value;
|
---|
646 |
|
---|
647 |
|
---|
648 | int indexOffspring = 0;
|
---|
649 | var mates = MatingSelection(rand, 2); // select parents
|
---|
650 | //var s1 = (IScope)population[mates[0]].Individual.Clone();
|
---|
651 | //var s2 = (IScope)population[mates[1]].Individual.Clone();
|
---|
652 | //var ages = population.Select(x => x.Age).ToArray();
|
---|
653 |
|
---|
654 | var s1 = (IScope)layerPopulation[counterLayerALPS][mates[0]].Individual.Clone();
|
---|
655 | var s2 = (IScope)layerPopulation[counterLayerALPS][mates[1]].Individual.Clone();
|
---|
656 | var ages = layerPopulation[counterLayerALPS].Select(x => x.Age).ToArray();
|
---|
657 |
|
---|
658 | var s1_age = ages[mates[0]];
|
---|
659 | var s2_age = ages[mates[1]];
|
---|
660 | int offSpringAge = 0;
|
---|
661 | s1.Parent = s2.Parent = globalScope;
|
---|
662 | IScope childScope = null;
|
---|
663 |
|
---|
664 | // crossoverProbability = crossoverProbability - 0.02* counterLayerALPS;
|
---|
665 | //var test = SampleGaussian(rand, 0, 1);
|
---|
666 |
|
---|
667 | //crossoverProbability = 1 / (1 + Math.Exp(-0.02 * SampleGaussian(rand, 0, 1)) * (1 - crossoverProbability) / crossoverProbability);
|
---|
668 |
|
---|
669 | if (crossoverProbability < 0.5)
|
---|
670 | crossoverProbability = 0.5;
|
---|
671 | else if(crossoverProbability > 0.95)
|
---|
672 | {
|
---|
673 | crossoverProbability = 0.95;
|
---|
674 | }
|
---|
675 | layerCrossoverProbability[counterLayerALPS] = crossoverProbability;
|
---|
676 |
|
---|
677 | // crossover
|
---|
678 | if (rand.NextDouble() < crossoverProbability) {
|
---|
679 | childScope = new Scope($"{mates[0]}+{mates[1]}") { Parent = executionContext.Scope };
|
---|
680 | childScope.SubScopes.Add(s1);
|
---|
681 | childScope.SubScopes.Add(s2);
|
---|
682 | var opCrossover = executionContext.CreateChildOperation(crossover, childScope);
|
---|
683 | ExecuteOperation(executionContext, innerToken, opCrossover);
|
---|
684 | offSpringAge = Math.Max(s1_age, s2_age) + 1;
|
---|
685 | childScope.SubScopes.Clear(); // <<-- VERY IMPORTANT!
|
---|
686 | }
|
---|
687 | else { // MUTATION POLISHI
|
---|
688 | if (childScope == null) {
|
---|
689 | offSpringAge = ages[mates[0]];
|
---|
690 | }
|
---|
691 | else {
|
---|
692 | }
|
---|
693 | childScope = childScope ?? s1;
|
---|
694 | var opMutation = executionContext.CreateChildOperation(mutator, childScope);
|
---|
695 | ExecuteOperation(executionContext, innerToken, opMutation);
|
---|
696 | offSpringAge = offSpringAge + 1;
|
---|
697 | }
|
---|
698 | if (childScope != null) { // Evaluate the childScope
|
---|
699 | var opEvaluation = executionContext.CreateChildOperation(evaluator, childScope);
|
---|
700 | ExecuteOperation(executionContext, innerToken, opEvaluation);
|
---|
701 | // childScope
|
---|
702 | var qualities = (DoubleArray)childScope.Variables["Qualities"].Value;
|
---|
703 | var childSolution = new DynamicALPSSolution(childScope, maximization.Length, 0);
|
---|
704 | // set child qualities
|
---|
705 | for (int j = 0; j < maximization.Length; ++j) {
|
---|
706 | childSolution.Qualities[j] = maximization[j] ? 1 - qualities[j] : qualities[j];
|
---|
707 | }
|
---|
708 | IdealPoint.UpdateIdeal(childSolution.Qualities);
|
---|
709 | NadirPoint.UpdateNadir(childSolution.Qualities);
|
---|
710 | // TODO, KF -- For later usage when $lambda > 1$
|
---|
711 | childSolution.HypervolumeContribution = null;
|
---|
712 | childSolution.NondominanceRanking = null;
|
---|
713 | childSolution.Age = offSpringAge;
|
---|
714 | layerOffspringPopulation[counterLayerALPS][indexOffspring] = childSolution;
|
---|
715 | ++evaluatedSolutions;
|
---|
716 | indexOffspring += 1;
|
---|
717 | }
|
---|
718 | else {
|
---|
719 | // no crossover or mutation were applied, a child was not produced, do nothing
|
---|
720 | }
|
---|
721 |
|
---|
722 |
|
---|
723 | layerJointPopulation[counterLayerALPS] = new IDynamicALPSSolution[populationSize + lambda];
|
---|
724 | layerPopulation[counterLayerALPS].CopyTo(layerJointPopulation[counterLayerALPS], 0);
|
---|
725 | layerOffspringPopulation[counterLayerALPS].CopyTo(layerJointPopulation[counterLayerALPS], populationSize);
|
---|
726 |
|
---|
727 | SmetricSelection(lambda, counterLayerALPS); // SMS-EMOA
|
---|
728 | return evaluatedSolutions;
|
---|
729 | }
|
---|
730 |
|
---|
731 |
|
---|
732 |
|
---|
733 |
|
---|
734 |
|
---|
735 |
|
---|
736 | // Update the Pareto-front approximation set and scatter the solutions in PF approximation set.
|
---|
737 | protected ResultCollection UpdateParetoFronts(IDynamicALPSSolution[] solutions, double[] IdealPoint) {
|
---|
738 |
|
---|
739 |
|
---|
740 | //var qualities = population.Select(x => Enumerable.Range(0, NadirPoint.Length).Select(i => x.Qualities[i] / NadirPoint[i]).ToArray()).ToArray();
|
---|
741 | var qualities = solutions.Select(x => x.Qualities).ToArray();
|
---|
742 | var maximization = Enumerable.Repeat(false, IdealPoint.Length).ToArray(); // DynamicALPS minimizes everything internally
|
---|
743 | var pf = DominationCalculator<IDynamicALPSSolution>.CalculateBestParetoFront(solutions, qualities, maximization);
|
---|
744 |
|
---|
745 | var pf2 = DominationCalculator<IDynamicALPSSolution>.CalculateAllParetoFronts(solutions, qualities, maximization, out int[] ranking);
|
---|
746 | var n = (int)EnumerableExtensions.BinomialCoefficient(IdealPoint.Length, 2);
|
---|
747 |
|
---|
748 |
|
---|
749 | // Struture hypervolume
|
---|
750 | // [0,0]: Value of HV
|
---|
751 | // [0,1]: PF size, $|PF|$
|
---|
752 | var hypervolumes = new DoubleMatrix(n == 1 ? 1 : n + 1, 2) { ColumnNames = new[] { "PF hypervolume", "PF size" } };
|
---|
753 |
|
---|
754 |
|
---|
755 | // HV calculation
|
---|
756 | // pf.Select(x => x.Item2): the "Item2" in var "pd"
|
---|
757 | // Enumerable.Repeat(1d, NadirPoint.Length).ToArray(): reference point
|
---|
758 | // maximization: type of optimization problem:
|
---|
759 | // True: maximization problem
|
---|
760 | // False: minimization problem
|
---|
761 | var reference = Enumerable.Repeat(double.MaxValue, maximization.Length).ToArray();
|
---|
762 | if (ReferencePoint is null) { // KF, 20200217 -- fix no reference point on real-world applications. If No reference points in Algorithms, use 1.1 \times max objective values as the reference point
|
---|
763 | for (int i = 0; i < reference.Length; i++) {
|
---|
764 | reference[i] = 1.1 * reference[i];
|
---|
765 | if (reference[i] > 10000) {
|
---|
766 | reference[i] = 9999; // set a upper bound for the reference point
|
---|
767 | }
|
---|
768 | }
|
---|
769 | }
|
---|
770 | else {
|
---|
771 | reference = ReferencePoint.ToArray();
|
---|
772 | }
|
---|
773 |
|
---|
774 | var nondominated = NonDominatedSelect.GetDominatingVectors(pf.Select(x => x.Item2), reference, maximization, false);
|
---|
775 | hypervolumes[0, 0] = nondominated.Any() ? Hypervolume.Calculate(nondominated, reference, maximization) : int.MinValue;
|
---|
776 |
|
---|
777 | //hypervolumes[0, 0] = Hypervolume.Calculate(pf.Select(x => x.Item2), reference, maximization);
|
---|
778 | hypervolumes[0, 1] = pf.Count;
|
---|
779 | Console.WriteLine("Current HV is", hypervolumes[0, 0]);
|
---|
780 |
|
---|
781 | var elementNames = new List<string>() { "Pareto Front" };
|
---|
782 | var results = new ResultCollection();
|
---|
783 |
|
---|
784 | ResultCollection innerResults;
|
---|
785 | if (results.ContainsKey("Hypervolume Analysis")) {
|
---|
786 | innerResults = (ResultCollection)results["Hypervolume Analysis"].Value;
|
---|
787 | }
|
---|
788 | else {
|
---|
789 | innerResults = new ResultCollection();
|
---|
790 | results.AddOrUpdateResult("Hypervolume Analysis", innerResults);
|
---|
791 | }
|
---|
792 |
|
---|
793 | ScatterPlot sp;
|
---|
794 | if (IdealPoint.Length == 2) {
|
---|
795 | var points = pf.Select(x => new Point2D<double>(x.Item2[0], x.Item2[1]));
|
---|
796 | var r = OnlinePearsonsRCalculator.Calculate(points.Select(x => x.X), points.Select(x => x.Y), out OnlineCalculatorError error);
|
---|
797 | if (error != OnlineCalculatorError.None) { r = double.NaN; }
|
---|
798 | var resultName = "Pareto Front Analysis ";
|
---|
799 | if (!innerResults.ContainsKey(resultName)) {
|
---|
800 | sp = new ScatterPlot() {
|
---|
801 | //VisualProperties = {
|
---|
802 | // XAxisMinimumAuto = true, XAxisMinimumFixedValue = 0d, XAxisMaximumAuto = false, XAxisMaximumFixedValue = 1d,
|
---|
803 | // YAxisMinimumAuto = true, YAxisMinimumFixedValue = 0d, YAxisMaximumAuto = false, YAxisMaximumFixedValue = 1d
|
---|
804 | //}
|
---|
805 | };
|
---|
806 | sp.Rows.Add(new ScatterPlotDataRow(resultName, "", points) { VisualProperties = { PointSize = 8 } });
|
---|
807 | innerResults.AddOrUpdateResult(resultName, sp);
|
---|
808 | }
|
---|
809 | else {
|
---|
810 | sp = (ScatterPlot)innerResults[resultName].Value;
|
---|
811 | sp.Rows[resultName].Points.Replace(points);
|
---|
812 | }
|
---|
813 | sp.Name = $"Dimensions [0, 1], correlation: {r.ToString("N2")}";
|
---|
814 | }
|
---|
815 | else if (IdealPoint.Length > 2) {
|
---|
816 | var indices = Enumerable.Range(0, IdealPoint.Length).ToArray();
|
---|
817 | var visualProperties = new ScatterPlotDataRowVisualProperties { PointSize = 8, Color = Color.LightGray };
|
---|
818 | var combinations = indices.Combinations(2).ToArray();
|
---|
819 | var maximization2d = new[] { false, false };
|
---|
820 | var solutions2d = pf.Select(x => x.Item1).ToArray();
|
---|
821 | for (int i = 0; i < combinations.Length; ++i) {
|
---|
822 | var c = combinations[i].ToArray();
|
---|
823 |
|
---|
824 | // calculate the hypervolume in the 2d coordinate space
|
---|
825 | var reference2d = new[] { 1d, 1d };
|
---|
826 | var qualities2d = pf.Select(x => new[] { x.Item2[c[0]], x.Item2[c[1]] }).ToArray();
|
---|
827 | var pf2d = DominationCalculator<IDynamicALPSSolution>.CalculateBestParetoFront(solutions2d, qualities2d, maximization2d);
|
---|
828 |
|
---|
829 | hypervolumes[i + 1, 0] = pf2d.Count > 0 ? Hypervolume.Calculate(pf2d.Select(x => x.Item2), reference2d, maximization2d) : 0d;
|
---|
830 | hypervolumes[i + 1, 1] = pf2d.Count;
|
---|
831 |
|
---|
832 | var resultName = $"Pareto Front Analysis [{c[0]}, {c[1]}]";
|
---|
833 | elementNames.Add(resultName);
|
---|
834 |
|
---|
835 | var points = pf.Select(x => new Point2D<double>(x.Item2[c[0]], x.Item2[c[1]]));
|
---|
836 | var pf2dPoints = pf2d.Select(x => new Point2D<double>(x.Item2[0], x.Item2[1]));
|
---|
837 |
|
---|
838 | if (!innerResults.ContainsKey(resultName)) {
|
---|
839 | sp = new ScatterPlot() {
|
---|
840 | VisualProperties = {
|
---|
841 | XAxisMinimumAuto = false, XAxisMinimumFixedValue = 0d, XAxisMaximumAuto = false, XAxisMaximumFixedValue = 1d,
|
---|
842 | YAxisMinimumAuto = false, YAxisMinimumFixedValue = 0d, YAxisMaximumAuto = false, YAxisMaximumFixedValue = 1d
|
---|
843 | }
|
---|
844 | };
|
---|
845 | sp.Rows.Add(new ScatterPlotDataRow("Pareto Front", "", points) { VisualProperties = visualProperties });
|
---|
846 | sp.Rows.Add(new ScatterPlotDataRow($"Pareto Front [{c[0]}, {c[1]}]", "", pf2dPoints) { VisualProperties = { PointSize = 10, Color = Color.OrangeRed } });
|
---|
847 | innerResults.AddOrUpdateResult(resultName, sp);
|
---|
848 | }
|
---|
849 | else {
|
---|
850 | sp = (ScatterPlot)innerResults[resultName].Value;
|
---|
851 | sp.Rows["Pareto Front"].Points.Replace(points);
|
---|
852 | sp.Rows[$"Pareto Front [{c[0]}, {c[1]}]"].Points.Replace(pf2dPoints);
|
---|
853 | }
|
---|
854 | var r = OnlinePearsonsRCalculator.Calculate(points.Select(x => x.X), points.Select(x => x.Y), out OnlineCalculatorError error);
|
---|
855 | var r2 = r * r;
|
---|
856 | sp.Name = $"Pareto Front [{c[0]}, {c[1]}], correlation: {r2.ToString("N2")}";
|
---|
857 | }
|
---|
858 | }
|
---|
859 | hypervolumes.RowNames = elementNames;
|
---|
860 | innerResults.AddOrUpdateResult("Hypervolumes", hypervolumes);
|
---|
861 |
|
---|
862 | return results;
|
---|
863 | }
|
---|
864 |
|
---|
865 | #region operator wiring and events
|
---|
866 | protected void ExecuteOperation(ExecutionContext executionContext, CancellationToken cancellationToken, IOperation operation) {
|
---|
867 | Stack<IOperation> executionStack = new Stack<IOperation>();
|
---|
868 | executionStack.Push(operation);
|
---|
869 | while (executionStack.Count > 0) {
|
---|
870 | cancellationToken.ThrowIfCancellationRequested();
|
---|
871 | IOperation next = executionStack.Pop();
|
---|
872 | if (next is OperationCollection) {
|
---|
873 | OperationCollection coll = (OperationCollection)next;
|
---|
874 | for (int i = coll.Count - 1; i >= 0; i--)
|
---|
875 | if (coll[i] != null) executionStack.Push(coll[i]);
|
---|
876 | }
|
---|
877 | else if (next is IAtomicOperation) {
|
---|
878 | IAtomicOperation op = (IAtomicOperation)next;
|
---|
879 | next = op.Operator.Execute((IExecutionContext)op, cancellationToken);
|
---|
880 | if (next != null) executionStack.Push(next);
|
---|
881 | }
|
---|
882 | }
|
---|
883 | }
|
---|
884 |
|
---|
885 | protected virtual void UpdateAnalyzers() {
|
---|
886 | Analyzer.Operators.Clear();
|
---|
887 | if (Problem != null) {
|
---|
888 | foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
|
---|
889 | foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
|
---|
890 | param.Depth = 1;
|
---|
891 | Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
|
---|
892 | }
|
---|
893 | }
|
---|
894 | }
|
---|
895 |
|
---|
896 | private void UpdateCrossovers() {
|
---|
897 | ICrossover oldCrossover = CrossoverParameter.Value;
|
---|
898 | CrossoverParameter.ValidValues.Clear();
|
---|
899 | ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
|
---|
900 |
|
---|
901 | foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
|
---|
902 | CrossoverParameter.ValidValues.Add(crossover);
|
---|
903 |
|
---|
904 | if (oldCrossover != null) {
|
---|
905 | ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
|
---|
906 | if (crossover != null) CrossoverParameter.Value = crossover;
|
---|
907 | else oldCrossover = null;
|
---|
908 | }
|
---|
909 | if (oldCrossover == null && defaultCrossover != null)
|
---|
910 | CrossoverParameter.Value = defaultCrossover;
|
---|
911 | }
|
---|
912 |
|
---|
913 | private void UpdateMutators() {
|
---|
914 | IManipulator oldMutator = MutatorParameter.Value;
|
---|
915 | MutatorParameter.ValidValues.Clear();
|
---|
916 | IManipulator defaultMutator = Problem.Operators.OfType<IManipulator>().FirstOrDefault();
|
---|
917 |
|
---|
918 | foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
|
---|
919 | MutatorParameter.ValidValues.Add(mutator);
|
---|
920 |
|
---|
921 | if (oldMutator != null) {
|
---|
922 | IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
|
---|
923 | if (mutator != null) MutatorParameter.Value = mutator;
|
---|
924 | else oldMutator = null;
|
---|
925 | }
|
---|
926 |
|
---|
927 | if (oldMutator == null && defaultMutator != null)
|
---|
928 | MutatorParameter.Value = defaultMutator;
|
---|
929 | }
|
---|
930 |
|
---|
931 | protected override void OnProblemChanged() {
|
---|
932 | UpdateCrossovers();
|
---|
933 | UpdateMutators();
|
---|
934 | UpdateAnalyzers();
|
---|
935 | base.OnProblemChanged();
|
---|
936 | }
|
---|
937 |
|
---|
938 | protected override void OnExecutionStateChanged() {
|
---|
939 | previousExecutionState = executionState;
|
---|
940 | executionState = ExecutionState;
|
---|
941 | base.OnExecutionStateChanged();
|
---|
942 | }
|
---|
943 |
|
---|
944 | public void ClearState() {
|
---|
945 | solutions = null;
|
---|
946 | population = null;
|
---|
947 | offspringPopulation = null;
|
---|
948 | //jointPopulation = null;
|
---|
949 | lambda_moead = null;
|
---|
950 | neighbourhood = null;
|
---|
951 | if (executionContext != null && executionContext.Scope != null) {
|
---|
952 | executionContext.Scope.SubScopes.Clear();
|
---|
953 | }
|
---|
954 | }
|
---|
955 |
|
---|
956 | protected override void OnStopped() {
|
---|
957 | ClearState();
|
---|
958 | base.OnStopped();
|
---|
959 | }
|
---|
960 | #endregion
|
---|
961 | }
|
---|
962 | }
|
---|