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

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

#2269

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