source: branches/ALPS/HeuristicLab.Algorithms.ALPS/3.3/AlpsGeneticAlgorithm.cs @ 12996

Last change on this file since 12996 was 12996, checked in by pfleck, 7 years ago

#2269

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