Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3107_LearningALPS/HeuristicLab.Algorithms.ALPS/3.3/AlpsGeneticAlgorithm.cs @ 17975

Last change on this file since 17975 was 17854, checked in by pfleck, 4 years ago

#3107 Added a new operator hook for ALPS for adapting the reinitialization strategy.

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