Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14908 was 14185, checked in by swagner, 8 years ago

#2526: Updated year of copyrights in license headers

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