Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2994-AutoDiffForIntervals/HeuristicLab.Algorithms.ALPS/3.3/AlpsOffspringSelectionGeneticAlgorithm.cs @ 17181

Last change on this file since 17181 was 16911, checked in by gkronber, 6 years ago

#2994: merged r16839:16910 from trunk to branch

File size: 40.7 KB
Line 
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
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HEAL.Attic;
26using HeuristicLab.Analysis;
27using HeuristicLab.Collections;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Operators;
32using HeuristicLab.Optimization;
33using HeuristicLab.Optimization.Operators;
34using HeuristicLab.Parameters;
35using HeuristicLab.PluginInfrastructure;
36using HeuristicLab.Random;
37using HeuristicLab.Selection;
38
39namespace HeuristicLab.Algorithms.ALPS {
40  [Item("ALPS OffspringSelection Genetic Algorithm", "An offspring selection genetic algorithm within an age-layered population structure.")]
41  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 162)]
42  [StorableType("4CA6AFE2-8EE9-4724-AA5C-624C734703FD")]
43  public sealed class AlpsOffspringSelectionGeneticAlgorithm : HeuristicOptimizationEngineAlgorithm, IStorableContent {
44    public string Filename { get; set; }
45
46    #region Problem Properties
47    public override Type ProblemType {
48      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
49    }
50    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
51      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
52      set { base.Problem = value; }
53    }
54    #endregion
55
56    #region Parameter Properties
57    private IFixedValueParameter<IntValue> SeedParameter {
58      get { return (IFixedValueParameter<IntValue>)Parameters["Seed"]; }
59    }
60    private IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
61      get { return (IFixedValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
62    }
63
64    private IFixedValueParameter<MultiAnalyzer> AnalyzerParameter {
65      get { return (IFixedValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
66    }
67    private IFixedValueParameter<MultiAnalyzer> LayerAnalyzerParameter {
68      get { return (IFixedValueParameter<MultiAnalyzer>)Parameters["LayerAnalyzer"]; }
69    }
70
71    private IFixedValueParameter<IntValue> NumberOfLayersParameter {
72      get { return (IFixedValueParameter<IntValue>)Parameters["NumberOfLayers"]; }
73    }
74    private IFixedValueParameter<IntValue> PopulationSizeParameter {
75      get { return (IFixedValueParameter<IntValue>)Parameters["PopulationSize"]; }
76    }
77
78    public IConstrainedValueParameter<ISelector> SelectorParameter {
79      get { return (IConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
80    }
81    public IConstrainedValueParameter<ICrossover> CrossoverParameter {
82      get { return (IConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
83    }
84    public IConstrainedValueParameter<IManipulator> MutatorParameter {
85      get { return (IConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
86    }
87    private IFixedValueParameter<PercentValue> MutationProbabilityParameter {
88      get { return (IFixedValueParameter<PercentValue>)Parameters["MutationProbability"]; }
89    }
90    private IFixedValueParameter<IntValue> ElitesParameter {
91      get { return (IFixedValueParameter<IntValue>)Parameters["Elites"]; }
92    }
93    private IFixedValueParameter<BoolValue> ReevaluateElitesParameter {
94      get { return (IFixedValueParameter<BoolValue>)Parameters["ReevaluateElites"]; }
95    }
96
97    private IFixedValueParameter<DoubleValue> SuccessRatioParameter {
98      get { return (IFixedValueParameter<DoubleValue>)Parameters["SuccessRatio"]; }
99    }
100    private IFixedValueParameter<DoubleValue> ComparisonFactorParameter {
101      get { return (IFixedValueParameter<DoubleValue>)Parameters["ComparisonFactor"]; }
102    }
103    private IFixedValueParameter<DoubleValue> MaximumSelectionPressureParameter {
104      get { return (IFixedValueParameter<DoubleValue>)Parameters["MaximumSelectionPressure"]; }
105    }
106    private IFixedValueParameter<BoolValue> OffspringSelectionBeforeMutationParameter {
107      get { return (IFixedValueParameter<BoolValue>)Parameters["OffspringSelectionBeforeMutation"]; }
108    }
109    private IFixedValueParameter<IntValue> SelectedParentsParameter {
110      get { return (IFixedValueParameter<IntValue>)Parameters["SelectedParents"]; }
111    }
112    private IFixedValueParameter<BoolValue> FillPopulationWithParentsParameter {
113      get { return (IFixedValueParameter<BoolValue>)Parameters["FillPopulationWithParents"]; }
114    }
115
116    private IFixedValueParameter<EnumValue<AgingScheme>> AgingSchemeParameter {
117      get { return (IFixedValueParameter<EnumValue<AgingScheme>>)Parameters["AgingScheme"]; }
118    }
119    private IFixedValueParameter<IntValue> AgeGapParameter {
120      get { return (IFixedValueParameter<IntValue>)Parameters["AgeGap"]; }
121    }
122    private IFixedValueParameter<DoubleValue> AgeInheritanceParameter {
123      get { return (IFixedValueParameter<DoubleValue>)Parameters["AgeInheritance"]; }
124    }
125    private IFixedValueParameter<IntArray> AgeLimitsParameter {
126      get { return (IFixedValueParameter<IntArray>)Parameters["AgeLimits"]; }
127    }
128
129    private IFixedValueParameter<IntValue> MatingPoolRangeParameter {
130      get { return (IFixedValueParameter<IntValue>)Parameters["MatingPoolRange"]; }
131    }
132    private IFixedValueParameter<BoolValue> ReduceToPopulationSizeParameter {
133      get { return (IFixedValueParameter<BoolValue>)Parameters["ReduceToPopulationSize"]; }
134    }
135
136    private IFixedValueParameter<MultiTerminator> TerminatorParameter {
137      get { return (IFixedValueParameter<MultiTerminator>)Parameters["Terminator"]; }
138    }
139    #endregion
140
141    #region Properties
142    public int Seed {
143      get { return SeedParameter.Value.Value; }
144      set { SeedParameter.Value.Value = value; }
145    }
146    public bool SetSeedRandomly {
147      get { return SetSeedRandomlyParameter.Value.Value; }
148      set { SetSeedRandomlyParameter.Value.Value = value; }
149    }
150
151    public MultiAnalyzer Analyzer {
152      get { return AnalyzerParameter.Value; }
153    }
154    public MultiAnalyzer LayerAnalyzer {
155      get { return LayerAnalyzerParameter.Value; }
156    }
157
158    public int NumberOfLayers {
159      get { return NumberOfLayersParameter.Value.Value; }
160      set { NumberOfLayersParameter.Value.Value = value; }
161    }
162    public int PopulationSize {
163      get { return PopulationSizeParameter.Value.Value; }
164      set { PopulationSizeParameter.Value.Value = value; }
165    }
166
167    public ISelector Selector {
168      get { return SelectorParameter.Value; }
169      set { SelectorParameter.Value = value; }
170    }
171    public ICrossover Crossover {
172      get { return CrossoverParameter.Value; }
173      set { CrossoverParameter.Value = value; }
174    }
175    public IManipulator Mutator {
176      get { return MutatorParameter.Value; }
177      set { MutatorParameter.Value = value; }
178    }
179    public double MutationProbability {
180      get { return MutationProbabilityParameter.Value.Value; }
181      set { MutationProbabilityParameter.Value.Value = value; }
182    }
183    public int Elites {
184      get { return ElitesParameter.Value.Value; }
185      set { ElitesParameter.Value.Value = value; }
186    }
187    public bool ReevaluteElites {
188      get { return ReevaluateElitesParameter.Value.Value; }
189      set { ReevaluateElitesParameter.Value.Value = value; }
190    }
191
192    public double SuccessRatio {
193      get { return SuccessRatioParameter.Value.Value; }
194      set { SuccessRatioParameter.Value.Value = value; }
195    }
196    public double ComparisonFactor {
197      get { return ComparisonFactorParameter.Value.Value; }
198      set { ComparisonFactorParameter.Value.Value = value; }
199    }
200    public double MaximumSelectionPressure {
201      get { return MaximumSelectionPressureParameter.Value.Value; }
202      set { MaximumSelectionPressureParameter.Value.Value = value; }
203    }
204    public bool OffspringSelectionBeforeMutation {
205      get { return OffspringSelectionBeforeMutationParameter.Value.Value; }
206      set { OffspringSelectionBeforeMutationParameter.Value.Value = value; }
207    }
208    public int SelectedParents {
209      get { return SelectedParentsParameter.Value.Value; }
210      set { SelectedParentsParameter.Value.Value = value; }
211    }
212    public bool FillPopulationWithParents {
213      get { return FillPopulationWithParentsParameter.Value.Value; }
214      set { FillPopulationWithParentsParameter.Value.Value = value; }
215    }
216
217    public AgingScheme AgingScheme {
218      get { return AgingSchemeParameter.Value.Value; }
219      set { AgingSchemeParameter.Value.Value = value; }
220    }
221    public int AgeGap {
222      get { return AgeGapParameter.Value.Value; }
223      set { AgeGapParameter.Value.Value = value; }
224    }
225    public double AgeInheritance {
226      get { return AgeInheritanceParameter.Value.Value; }
227      set { AgeInheritanceParameter.Value.Value = value; }
228    }
229    public IntArray AgeLimits {
230      get { return AgeLimitsParameter.Value; }
231      set {
232        AgeLimits.Length = value.Length;
233        for (int i = 0; i < value.Length; i++)
234          AgeLimits[i] = value[i];
235      }
236    }
237
238    public int MatingPoolRange {
239      get { return MatingPoolRangeParameter.Value.Value; }
240      set { MatingPoolRangeParameter.Value.Value = value; }
241    }
242
243    public MultiTerminator Terminators {
244      get { return TerminatorParameter.Value; }
245    }
246
247    public int MaximumGenerations {
248      get { return generationsTerminator.Threshold.Value; }
249      set { generationsTerminator.Threshold.Value = value; }
250    }
251    #endregion
252
253    #region Helper Properties
254    private SolutionsCreator SolutionsCreator {
255      get { return OperatorGraph.Iterate().OfType<SolutionsCreator>().First(); }
256    }
257    private AlpsOffspringSelectionGeneticAlgorithmMainLoop MainLoop {
258      get { return OperatorGraph.Iterate().OfType<AlpsOffspringSelectionGeneticAlgorithmMainLoop>().First(); }
259    }
260    #endregion
261
262    #region Preconfigured Analyzers
263    [Storable]
264    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
265    [Storable]
266    private BestAverageWorstQualityAnalyzer layerQualityAnalyzer;
267    [Storable]
268    private OldestAverageYoungestAgeAnalyzer ageAnalyzer;
269    [Storable]
270    private OldestAverageYoungestAgeAnalyzer layerAgeAnalyzer;
271    [Storable]
272    private AgeDistributionAnalyzer ageDistributionAnalyzer;
273    [Storable]
274    private AgeDistributionAnalyzer layerAgeDistributionAnalyzer;
275    [Storable]
276    private ValueAnalyzer selectionPressureAnalyzer;
277    [Storable]
278    private ValueAnalyzer layerSelectionPressureAnalyzer;
279    [Storable]
280    private ValueAnalyzer currentSuccessRatioAnalyzer;
281    #endregion
282
283    #region Preconfigured Terminators
284    [Storable]
285    private ComparisonTerminator<IntValue> generationsTerminator;
286    [Storable]
287    private ComparisonTerminator<IntValue> evaluationsTerminator;
288    [Storable]
289    private SingleObjectiveQualityTerminator qualityTerminator;
290    [Storable]
291    private ExecutionTimeTerminator executionTimeTerminator;
292    #endregion
293
294    #region Constructors
295    [StorableConstructor]
296    private AlpsOffspringSelectionGeneticAlgorithm(StorableConstructorFlag _) : base(_) { }
297    [StorableHook(HookType.AfterDeserialization)]
298    private void AfterDeserialization() {
299      // BackwardsCompatibility3.3
300      #region Backwards compatible code, remove with 3.4
301      var optionalMutatorParameter = MutatorParameter as OptionalConstrainedValueParameter<IManipulator>;
302      if (optionalMutatorParameter != null) {
303        Parameters.Remove(optionalMutatorParameter);
304        Parameters.Add(new ConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
305        foreach (var m in optionalMutatorParameter.ValidValues)
306          MutatorParameter.ValidValues.Add(m);
307        if (optionalMutatorParameter.Value == null) MutationProbability = 0; // to guarantee that the old configuration results in the same behavior
308        else Mutator = optionalMutatorParameter.Value;
309        optionalMutatorParameter.ValidValues.Clear(); // to avoid dangling references to the old parameter its valid values are cleared
310      }
311      #endregion
312      Initialize();
313    }
314    private AlpsOffspringSelectionGeneticAlgorithm(AlpsOffspringSelectionGeneticAlgorithm original, Cloner cloner)
315      : base(original, cloner) {
316      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
317      layerQualityAnalyzer = cloner.Clone(original.layerQualityAnalyzer);
318      ageAnalyzer = cloner.Clone(original.ageAnalyzer);
319      layerAgeAnalyzer = cloner.Clone(original.layerAgeAnalyzer);
320      ageDistributionAnalyzer = cloner.Clone(original.ageDistributionAnalyzer);
321      layerAgeDistributionAnalyzer = cloner.Clone(original.layerAgeDistributionAnalyzer);
322      selectionPressureAnalyzer = cloner.Clone(original.selectionPressureAnalyzer);
323      layerSelectionPressureAnalyzer = cloner.Clone(original.layerSelectionPressureAnalyzer);
324      currentSuccessRatioAnalyzer = cloner.Clone(original.currentSuccessRatioAnalyzer);
325      generationsTerminator = cloner.Clone(original.generationsTerminator);
326      evaluationsTerminator = cloner.Clone(original.evaluationsTerminator);
327      qualityTerminator = cloner.Clone(original.qualityTerminator);
328      executionTimeTerminator = cloner.Clone(original.executionTimeTerminator);
329      Initialize();
330    }
331    public override IDeepCloneable Clone(Cloner cloner) {
332      return new AlpsOffspringSelectionGeneticAlgorithm(this, cloner);
333    }
334    public AlpsOffspringSelectionGeneticAlgorithm()
335      : base() {
336      #region Add parameters
337      Parameters.Add(new FixedValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
338      Parameters.Add(new FixedValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
339
340      Parameters.Add(new FixedValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze all individuals from all layers combined.", new MultiAnalyzer()));
341      Parameters.Add(new FixedValueParameter<MultiAnalyzer>("LayerAnalyzer", "The operator used to analyze each layer.", new MultiAnalyzer()));
342
343      Parameters.Add(new FixedValueParameter<IntValue>("NumberOfLayers", "The number of layers.", new IntValue(10)));
344      Parameters.Add(new FixedValueParameter<IntValue>("PopulationSize", "The size of the population of solutions in each layer.", new IntValue(100)));
345
346      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
347      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
348      Parameters.Add(new ConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
349      Parameters.Add(new FixedValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
350      Parameters.Add(new FixedValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
351      Parameters.Add(new FixedValueParameter<BoolValue>("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)", new BoolValue(false)) { Hidden = true });
352
353      Parameters.Add(new FixedValueParameter<DoubleValue>("SuccessRatio", "The ratio of successful to total children that should be achieved.", new DoubleValue(1)));
354      Parameters.Add(new FixedValueParameter<DoubleValue>("ComparisonFactor", "The comparison factor is used to determine whether the offspring should be compared to the better parent, the worse parent or a quality value linearly interpolated between them. It is in the range [0;1].", new DoubleValue(1)));
355      Parameters.Add(new FixedValueParameter<DoubleValue>("MaximumSelectionPressure", "The maximum selection pressure that terminates the algorithm.", new DoubleValue(100)));
356      Parameters.Add(new FixedValueParameter<BoolValue>("OffspringSelectionBeforeMutation", "True if the offspring selection step should be applied before mutation, false if it should be applied after mutation.", new BoolValue(false)));
357      Parameters.Add(new FixedValueParameter<IntValue>("SelectedParents", "How much parents should be selected each time the offspring selection step is performed until the population is filled. This parameter should be about the same or twice the size of PopulationSize for smaller problems, and less for large problems.", new IntValue(200)));
358      Parameters.Add(new FixedValueParameter<BoolValue>("FillPopulationWithParents", "True if the population should be filled with parent individual or false if worse children should be used when the maximum selection pressure is exceeded.", new BoolValue(false)) { Hidden = true });
359
360      Parameters.Add(new FixedValueParameter<EnumValue<AgingScheme>>("AgingScheme", "The aging scheme for setting the age-limits for the layers.", new EnumValue<AgingScheme>(ALPS.AgingScheme.Polynomial)));
361      Parameters.Add(new FixedValueParameter<IntValue>("AgeGap", "The frequency of reseeding the lowest layer and scaling factor for the age-limits for the layers.", new IntValue(20)));
362      Parameters.Add(new FixedValueParameter<DoubleValue>("AgeInheritance", "A weight that determines the age of a child after crossover based on the older (1.0) and younger (0.0) parent.", new DoubleValue(1.0)) { Hidden = true });
363      Parameters.Add(new FixedValueParameter<IntArray>("AgeLimits", "The maximum age an individual is allowed to reach in a certain layer.", new IntArray(new int[0])) { Hidden = true });
364
365      Parameters.Add(new FixedValueParameter<IntValue>("MatingPoolRange", "The range of layers used for creating a mating pool. (1 = current + previous layer)", new IntValue(1)) { Hidden = true });
366      Parameters.Add(new FixedValueParameter<BoolValue>("ReduceToPopulationSize", "Reduce the CurrentPopulationSize after elder migration to PopulationSize", new BoolValue(true)) { Hidden = true });
367
368      Parameters.Add(new FixedValueParameter<MultiTerminator>("Terminator", "The termination criteria that defines if the algorithm should continue or stop.", new MultiTerminator()));
369      #endregion
370
371      #region Create operators
372      var globalRandomCreator = new RandomCreator();
373      var layer0Creator = new SubScopesCreator() { Name = "Create Layer Zero" };
374      var layer0Processor = new SubScopesProcessor();
375      var localRandomCreator = new LocalRandomCreator();
376      var layerSolutionsCreator = new SolutionsCreator();
377      var initializeAgeProcessor = new UniformSubScopesProcessor();
378      var initializeAge = new VariableCreator() { Name = "Initialize Age" };
379      var initializeCurrentPopulationSize = new SubScopesCounter() { Name = "Initialize CurrentPopulationCounter" };
380      var initializeLocalEvaluatedSolutions = new Assigner() { Name = "Initialize LayerEvaluatedSolutions" };
381      var initializeGlobalEvaluatedSolutions = new DataReducer() { Name = "Initialize EvaluatedSolutions" };
382      var resultsCollector = new ResultsCollector();
383      var mainLoop = new AlpsOffspringSelectionGeneticAlgorithmMainLoop();
384      #endregion
385
386      #region Create and parameterize operator graph
387      OperatorGraph.InitialOperator = globalRandomCreator;
388
389      globalRandomCreator.RandomParameter.ActualName = "GlobalRandom";
390      globalRandomCreator.SeedParameter.Value = null;
391      globalRandomCreator.SeedParameter.ActualName = SeedParameter.Name;
392      globalRandomCreator.SetSeedRandomlyParameter.Value = null;
393      globalRandomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
394      globalRandomCreator.Successor = layer0Creator;
395
396      layer0Creator.NumberOfSubScopesParameter.Value = new IntValue(1);
397      layer0Creator.Successor = layer0Processor;
398
399      layer0Processor.Operators.Add(localRandomCreator);
400      layer0Processor.Successor = initializeGlobalEvaluatedSolutions;
401
402      localRandomCreator.Successor = layerSolutionsCreator;
403
404      layerSolutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
405      layerSolutionsCreator.Successor = initializeAgeProcessor;
406
407      initializeAgeProcessor.Operator = initializeAge;
408      initializeAgeProcessor.Successor = initializeCurrentPopulationSize;
409
410      initializeCurrentPopulationSize.ValueParameter.ActualName = "CurrentPopulationSize";
411      initializeCurrentPopulationSize.Successor = initializeLocalEvaluatedSolutions;
412
413      initializeAge.CollectedValues.Add(new ValueParameter<DoubleValue>("Age", new DoubleValue(0)));
414      initializeAge.Successor = null;
415
416      initializeLocalEvaluatedSolutions.LeftSideParameter.ActualName = "LayerEvaluatedSolutions";
417      initializeLocalEvaluatedSolutions.RightSideParameter.ActualName = "CurrentPopulationSize";
418      initializeLocalEvaluatedSolutions.Successor = null;
419
420      initializeGlobalEvaluatedSolutions.ReductionOperation.Value.Value = ReductionOperations.Sum;
421      initializeGlobalEvaluatedSolutions.TargetOperation.Value.Value = ReductionOperations.Assign;
422      initializeGlobalEvaluatedSolutions.ParameterToReduce.ActualName = "LayerEvaluatedSolutions";
423      initializeGlobalEvaluatedSolutions.TargetParameter.ActualName = "EvaluatedSolutions";
424      initializeGlobalEvaluatedSolutions.Successor = resultsCollector;
425
426      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
427      resultsCollector.Successor = mainLoop;
428
429      mainLoop.GlobalRandomParameter.ActualName = "GlobalRandom";
430      mainLoop.LocalRandomParameter.ActualName = localRandomCreator.LocalRandomParameter.Name;
431      mainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
432      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
433      mainLoop.LayerAnalyzerParameter.ActualName = LayerAnalyzerParameter.Name;
434      mainLoop.NumberOfLayersParameter.ActualName = NumberOfLayersParameter.Name;
435      mainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
436      mainLoop.CurrentPopulationSizeParameter.ActualName = "CurrentPopulationSize";
437      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
438      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
439      mainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
440      mainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
441      mainLoop.ElitesParameter.ActualName = ElitesParameter.Name;
442      mainLoop.ReevaluateElitesParameter.ActualName = ReevaluateElitesParameter.Name;
443      mainLoop.SuccessRatioParameter.ActualName = SuccessRatioParameter.Name;
444      mainLoop.ComparisonFactorParameter.ActualName = ComparisonFactorParameter.Name;
445      mainLoop.MaximumSelectionPressureParameter.ActualName = MaximumSelectionPressureParameter.Name;
446      mainLoop.OffspringSelectionBeforeMutationParameter.ActualName = OffspringSelectionBeforeMutationParameter.Name;
447      mainLoop.FillPopulationWithParentsParameter.ActualName = FillPopulationWithParentsParameter.Name;
448      mainLoop.AgeParameter.ActualName = "Age";
449      mainLoop.AgeGapParameter.ActualName = AgeGapParameter.Name;
450      mainLoop.AgeInheritanceParameter.ActualName = AgeInheritanceParameter.Name;
451      mainLoop.AgeLimitsParameter.ActualName = AgeLimitsParameter.Name;
452      mainLoop.MatingPoolRangeParameter.ActualName = MatingPoolRangeParameter.Name;
453      mainLoop.ReduceToPopulationSizeParameter.ActualName = ReduceToPopulationSizeParameter.Name;
454      mainLoop.TerminatorParameter.ActualName = TerminatorParameter.Name;
455      #endregion
456
457      #region Set operators
458      foreach (var selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(s => !(s is IMultiObjectiveSelector)).OrderBy(s => Name))
459        SelectorParameter.ValidValues.Add(selector);
460      var defaultSelector = SelectorParameter.ValidValues.OfType<GeneralizedRankSelector>().FirstOrDefault();
461      if (defaultSelector != null) {
462        defaultSelector.PressureParameter.Value = new DoubleValue(4.0);
463        SelectorParameter.Value = defaultSelector;
464      }
465      #endregion
466
467      #region Create analyzers
468      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
469      layerQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
470      ageAnalyzer = new OldestAverageYoungestAgeAnalyzer();
471      layerAgeAnalyzer = new OldestAverageYoungestAgeAnalyzer();
472      ageDistributionAnalyzer = new AgeDistributionAnalyzer();
473      layerAgeDistributionAnalyzer = new AgeDistributionAnalyzer();
474      selectionPressureAnalyzer = new ValueAnalyzer();
475      layerSelectionPressureAnalyzer = new ValueAnalyzer();
476      currentSuccessRatioAnalyzer = new ValueAnalyzer();
477      #endregion
478
479      #region Create terminators
480      generationsTerminator = new ComparisonTerminator<IntValue>("Generations", ComparisonType.Less, new IntValue(1000)) { Name = "Generations" };
481      evaluationsTerminator = new ComparisonTerminator<IntValue>("EvaluatedSolutions", ComparisonType.Less, new IntValue(int.MaxValue)) { Name = "Evaluations" };
482      qualityTerminator = new SingleObjectiveQualityTerminator() { Name = "Quality" };
483      executionTimeTerminator = new ExecutionTimeTerminator(this, new TimeSpanValue(TimeSpan.FromMinutes(5)));
484      #endregion
485
486      #region Parameterize
487      UpdateAnalyzers();
488      ParameterizeAnalyzers();
489
490      ParameterizeSelectors();
491
492      UpdateTerminators();
493
494      ParameterizeAgeLimits();
495      #endregion
496
497      Initialize();
498    }
499    #endregion
500
501    #region Events
502    public override void Prepare() {
503      if (Problem != null)
504        base.Prepare();
505    }
506    protected override void OnProblemChanged() {
507      base.OnProblemChanged();
508      ParameterizeStochasticOperator(Problem.SolutionCreator);
509      foreach (var @operator in Problem.Operators.OfType<IOperator>())
510        ParameterizeStochasticOperator(@operator);
511      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
512
513      ParameterizeIterationBasedOperators();
514
515      ParameterizeSolutionsCreator();
516      ParameterizeMainLoop();
517      ParameterizeAnalyzers();
518      ParameterizeSelectors();
519      ParameterizeTerminators();
520
521      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
522
523      UpdateAnalyzers();
524      UpdateCrossovers();
525      UpdateMutators();
526      UpdateTerminators();
527    }
528
529    protected override void RegisterProblemEvents() {
530      base.RegisterProblemEvents();
531      var maximizationParameter = (IValueParameter<BoolValue>)Problem.MaximizationParameter;
532      if (maximizationParameter != null) maximizationParameter.ValueChanged += new EventHandler(MaximizationParameter_ValueChanged);
533    }
534    protected override void DeregisterProblemEvents() {
535      var maximizationParameter = (IValueParameter<BoolValue>)Problem.MaximizationParameter;
536      if (maximizationParameter != null) maximizationParameter.ValueChanged -= new EventHandler(MaximizationParameter_ValueChanged);
537      base.DeregisterProblemEvents();
538    }
539
540    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
541      base.Problem_SolutionCreatorChanged(sender, e);
542      ParameterizeStochasticOperator(Problem.SolutionCreator);
543
544      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
545
546      ParameterizeSolutionsCreator();
547      ParameterizeAnalyzers();
548    }
549    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
550      base.Problem_EvaluatorChanged(sender, e);
551      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
552
553      UpdateAnalyzers();
554
555      ParameterizeSolutionsCreator();
556      ParameterizeMainLoop();
557      ParameterizeSelectors();
558    }
559    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
560      base.Problem_OperatorsChanged(sender, e);
561      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
562      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
563      ParameterizeIterationBasedOperators();
564      UpdateCrossovers();
565      UpdateMutators();
566      UpdateTerminators();
567    }
568    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
569      ParameterizeMainLoop();
570      ParameterizeAnalyzers();
571      ParameterizeSelectors();
572    }
573    private void MaximizationParameter_ValueChanged(object sender, EventArgs e) {
574      ParameterizeTerminators();
575    }
576    private void QualityAnalyzer_CurrentBestQualityParameter_NameChanged(object sender, EventArgs e) {
577      ParameterizeTerminators();
578    }
579
580    private void AgeGap_ValueChanged(object sender, EventArgs e) {
581      ParameterizeAgeLimits();
582    }
583    private void AgingScheme_ValueChanged(object sender, EventArgs e) {
584      ParameterizeAgeLimits();
585    }
586    private void NumberOfLayers_ValueChanged(object sender, EventArgs e) {
587      ParameterizeAgeLimits();
588    }
589
590    private void AnalyzerOperators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IAnalyzer>> e) {
591      foreach (var analyzer in e.Items) {
592        foreach (var parameter in analyzer.Value.Parameters.OfType<IScopeTreeLookupParameter>()) {
593          parameter.Depth = 2;
594        }
595      }
596    }
597    private void LayerAnalyzerOperators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IAnalyzer>> e) {
598      foreach (var analyzer in e.Items) {
599        IParameter resultParameter;
600        if (analyzer.Value.Parameters.TryGetValue("Results", out resultParameter)) {
601          var lookupParameter = resultParameter as ILookupParameter;
602          if (lookupParameter != null)
603            lookupParameter.ActualName = "LayerResults";
604        }
605        foreach (var parameter in analyzer.Value.Parameters.OfType<IScopeTreeLookupParameter>()) {
606          parameter.Depth = 1;
607        }
608      }
609    }
610    #endregion
611
612    #region Parameterization
613    private void Initialize() {
614      if (Problem != null)
615        Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
616
617      NumberOfLayersParameter.Value.ValueChanged += NumberOfLayers_ValueChanged;
618
619      Analyzer.Operators.ItemsAdded += AnalyzerOperators_ItemsAdded;
620      LayerAnalyzer.Operators.ItemsAdded += LayerAnalyzerOperators_ItemsAdded;
621
622      AgeGapParameter.Value.ValueChanged += AgeGap_ValueChanged;
623      AgingSchemeParameter.Value.ValueChanged += AgingScheme_ValueChanged;
624
625      qualityAnalyzer.CurrentBestQualityParameter.NameChanged += QualityAnalyzer_CurrentBestQualityParameter_NameChanged;
626    }
627    private void ParameterizeSolutionsCreator() {
628      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
629      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
630    }
631    private void ParameterizeMainLoop() {
632      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
633      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
634      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
635    }
636    private void ParameterizeAnalyzers() {
637      qualityAnalyzer.ResultsParameter.ActualName = "Results";
638      qualityAnalyzer.ResultsParameter.Hidden = true;
639      qualityAnalyzer.QualityParameter.Depth = 2;
640      layerQualityAnalyzer.ResultsParameter.ActualName = "LayerResults";
641      layerQualityAnalyzer.ResultsParameter.Hidden = true;
642      layerQualityAnalyzer.QualityParameter.Depth = 1;
643      selectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
644      selectionPressureAnalyzer.ResultsParameter.ActualName = "Results";
645      selectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
646      selectionPressureAnalyzer.ValueParameter.Depth = 1;
647      selectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
648      layerSelectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
649      layerSelectionPressureAnalyzer.ResultsParameter.ActualName = "LayerResults";
650      layerSelectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
651      layerSelectionPressureAnalyzer.ValueParameter.Depth = 0;
652      layerSelectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
653      currentSuccessRatioAnalyzer.Name = "CurrentSuccessRatio Analyzer";
654      currentSuccessRatioAnalyzer.ResultsParameter.ActualName = "Results";
655      currentSuccessRatioAnalyzer.ValueParameter.ActualName = "CurrentSuccessRatio";
656      currentSuccessRatioAnalyzer.ValueParameter.Depth = 1;
657      currentSuccessRatioAnalyzer.ValuesParameter.ActualName = "Success Ratio History";
658      if (Problem != null) {
659        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
660        qualityAnalyzer.MaximizationParameter.Hidden = true;
661        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
662        qualityAnalyzer.QualityParameter.Hidden = true;
663        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
664        qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
665        layerQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
666        layerQualityAnalyzer.MaximizationParameter.Hidden = true;
667        layerQualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
668        layerQualityAnalyzer.QualityParameter.Hidden = true;
669        layerQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
670        layerQualityAnalyzer.BestKnownQualityParameter.Hidden = true;
671      }
672    }
673    private void ParameterizeSelectors() {
674      foreach (var selector in SelectorParameter.ValidValues) {
675        selector.CopySelected = new BoolValue(true);
676        selector.NumberOfSelectedSubScopesParameter.Hidden = true;
677        selector.NumberOfSelectedSubScopesParameter.ActualName = SelectedParentsParameter.Name;
678        ParameterizeStochasticOperatorForLayer(selector);
679      }
680      if (Problem != null) {
681        foreach (var selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
682          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
683          selector.MaximizationParameter.Hidden = true;
684          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
685          selector.QualityParameter.Hidden = true;
686        }
687      }
688    }
689    private void ParameterizeTerminators() {
690      qualityTerminator.Parameterize(qualityAnalyzer.CurrentBestQualityParameter, Problem);
691    }
692    private void ParameterizeIterationBasedOperators() {
693      if (Problem != null) {
694        foreach (var @operator in Problem.Operators.OfType<IIterationBasedOperator>()) {
695          @operator.IterationsParameter.ActualName = "Generations";
696          @operator.IterationsParameter.Hidden = true;
697          @operator.MaximumIterationsParameter.ActualName = generationsTerminator.ThresholdParameter.Name;
698          @operator.MaximumIterationsParameter.Hidden = true;
699        }
700      }
701    }
702    private void ParameterizeAgeLimits() {
703      AgeLimits = AgingScheme.CalculateAgeLimits(AgeGap, NumberOfLayers);
704    }
705
706    private void ParameterizeStochasticOperator(IOperator @operator) {
707      var stochasticOperator = @operator as IStochasticOperator;
708      if (stochasticOperator != null) {
709        stochasticOperator.RandomParameter.ActualName = "GlobalRandom";
710        stochasticOperator.RandomParameter.Hidden = true;
711      }
712    }
713
714    private void ParameterizeStochasticOperatorForLayer(IOperator @operator) {
715      var stochasticOperator = @operator as IStochasticOperator;
716      if (stochasticOperator != null) {
717        stochasticOperator.RandomParameter.ActualName = "LocalRandom";
718        stochasticOperator.RandomParameter.Hidden = true;
719      }
720    }
721
722    #endregion
723
724    #region Updates
725    private void UpdateAnalyzers() {
726      Analyzer.Operators.Clear();
727      LayerAnalyzer.Operators.Clear();
728
729      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
730      Analyzer.Operators.Add(ageAnalyzer, ageAnalyzer.EnabledByDefault);
731      Analyzer.Operators.Add(ageDistributionAnalyzer, ageDistributionAnalyzer.EnabledByDefault);
732      Analyzer.Operators.Add(selectionPressureAnalyzer, false);
733      selectionPressureAnalyzer.ValueParameter.Depth = 1; // Adding analyzer sets depth to 2
734      Analyzer.Operators.Add(currentSuccessRatioAnalyzer, false);
735      currentSuccessRatioAnalyzer.ValueParameter.Depth = 1; // Adding analyzer sets depth to 2
736      LayerAnalyzer.Operators.Add(layerQualityAnalyzer, false);
737      LayerAnalyzer.Operators.Add(layerAgeAnalyzer, false);
738      LayerAnalyzer.Operators.Add(layerAgeDistributionAnalyzer, false);
739      LayerAnalyzer.Operators.Add(layerSelectionPressureAnalyzer, false);
740      layerSelectionPressureAnalyzer.ValueParameter.Depth = 0; // Adding layer-analyzer sets depth to 1
741
742
743      if (Problem != null) {
744        foreach (var analyzer in Problem.Operators.OfType<IAnalyzer>()) {
745          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
746          LayerAnalyzer.Operators.Add((IAnalyzer)analyzer.Clone(), false);
747        }
748      }
749    }
750    private void UpdateCrossovers() {
751      var oldCrossover = CrossoverParameter.Value;
752      var defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
753      CrossoverParameter.ValidValues.Clear();
754      foreach (var crossover in Problem.Operators.OfType<ICrossover>().OrderBy(c => c.Name)) {
755        ParameterizeStochasticOperatorForLayer(crossover);
756        CrossoverParameter.ValidValues.Add(crossover);
757      }
758      if (oldCrossover != null) {
759        var crossover = CrossoverParameter.ValidValues.FirstOrDefault(c => c.GetType() == oldCrossover.GetType());
760        if (crossover != null)
761          CrossoverParameter.Value = crossover;
762        else
763          oldCrossover = null;
764      }
765      if (oldCrossover == null && defaultCrossover != null)
766        CrossoverParameter.Value = defaultCrossover;
767    }
768    private void UpdateMutators() {
769      IManipulator oldMutator = MutatorParameter.Value;
770      MutatorParameter.ValidValues.Clear();
771      IManipulator defaultMutator = Problem.Operators.OfType<IManipulator>().FirstOrDefault();
772
773      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name)) {
774        ParameterizeStochasticOperatorForLayer(mutator);
775        MutatorParameter.ValidValues.Add(mutator);
776      }
777
778      if (oldMutator != null) {
779        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
780        if (mutator != null) MutatorParameter.Value = mutator;
781        else oldMutator = null;
782      }
783
784      if (oldMutator == null && defaultMutator != null)
785        MutatorParameter.Value = defaultMutator;
786    }
787    private void UpdateTerminators() {
788      var newTerminators = new Dictionary<ITerminator, bool> {
789        {generationsTerminator, !Terminators.Operators.Contains(generationsTerminator) || Terminators.Operators.ItemChecked(generationsTerminator)},
790        {evaluationsTerminator, Terminators.Operators.Contains(evaluationsTerminator) && Terminators.Operators.ItemChecked(evaluationsTerminator)},
791        {qualityTerminator, Terminators.Operators.Contains(qualityTerminator) && Terminators.Operators.ItemChecked(qualityTerminator) },
792        {executionTimeTerminator, Terminators.Operators.Contains(executionTimeTerminator) && Terminators.Operators.ItemChecked(executionTimeTerminator)}
793      };
794      if (Problem != null) {
795        foreach (var terminator in Problem.Operators.OfType<ITerminator>())
796          newTerminators.Add(terminator, !Terminators.Operators.Contains(terminator) || Terminators.Operators.ItemChecked(terminator));
797      }
798
799      Terminators.Operators.Clear();
800
801      foreach (var newTerminator in newTerminators)
802        Terminators.Operators.Add(newTerminator.Key, newTerminator.Value);
803    }
804    #endregion
805  }
806}
Note: See TracBrowser for help on using the repository browser.