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

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

#2269

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