Free cookie consent management tool by TermsFeed Policy Generator

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

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

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

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