Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.ALPS/3.3/AlpsOffspringSelectionGeneticAlgorithm.cs @ 13791

Last change on this file since 13791 was 13402, checked in by pfleck, 9 years ago

#2527 Implemented ALPS-OSGA on the base of the AlpsGeneticAlgorithm and and the OffspringSelectionGeneticAlgorithmMainOperator.

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