Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Algorithms.ALPS/3.3/AlpsGeneticAlgorithm.cs @ 17401

Last change on this file since 17401 was 17198, checked in by mkommend, 5 years ago

#3020: Adapated AfterDeserializationHook of genetic algorithms to check if the mutator parameter already has the correct type.
In detail the following algorithms have been adapted: ALPS-GA, ALPS-OSGA, GA, Island-GA, NSGA-2, Island-OSGA, OSGA, SASEGASA.

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