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

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

#2269

  • Added the possibility of continuous reseeding (percentage based reseeding of layer 0).
  • Restructured operator graph.
  • Deleted LayerUpdator (replaced by LayerOpener`)
  • Deleted LayerSorter.
  • Moved preparing of GeneticAlgorithmMainLoop to AlpsGeneticAlgorithmMainOperator.
File size: 33.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Analysis;
26using HeuristicLab.Collections;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Operators;
31using HeuristicLab.Optimization;
32using HeuristicLab.Optimization.Operators;
33using HeuristicLab.Parameters;
34using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
35using HeuristicLab.PluginInfrastructure;
36using HeuristicLab.Random;
37using HeuristicLab.Selection;
38
39namespace HeuristicLab.Algorithms.ALPS {
40  [Item("ALPS Genetic Algorithm", "A genetic algorithm within an age-layered population structure as described in Gregory S. Hornby. 2006. ALPS: the age-layered population structure for reducing the problem of premature convergence. In Proceedings of the 8th annual conference on Genetic and evolutionary computation (GECCO '06). 815-822.")]
41  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 160)]
42  [StorableClass]
43  public sealed class AlpsGeneticAlgorithm : HeuristicOptimizationEngineAlgorithm, IStorableContent {
44    public string Filename { get; set; }
45
46    #region Problem Properties
47    public override Type ProblemType {
48      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
49    }
50    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
51      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
52      set { base.Problem = value; }
53    }
54    #endregion
55
56    #region Parameter Properties
57    private IValueParameter<IntValue> SeedParameter {
58      get { return (IValueParameter<IntValue>)Parameters["Seed"]; }
59    }
60    private IValueParameter<BoolValue> SetSeedRandomlyParameter {
61      get { return (IValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
62    }
63
64    private IFixedValueParameter<MultiAnalyzer> AnalyzerParameter {
65      get { return (IFixedValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
66    }
67    private IFixedValueParameter<MultiAnalyzer> LayerAnalyzerParameter {
68      get { return (IFixedValueParameter<MultiAnalyzer>)Parameters["LayerAnalyzer"]; }
69    }
70
71    private IValueParameter<IntValue> NumberOfLayersParameter {
72      get { return (IValueParameter<IntValue>)Parameters["NumberOfLayers"]; }
73    }
74    private IValueParameter<IntValue> PopulationSizeParameter {
75      get { return (IValueParameter<IntValue>)Parameters["PopulationSize"]; }
76    }
77
78    public IConstrainedValueParameter<ISelector> SelectorParameter {
79      get { return (IConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
80    }
81    public IConstrainedValueParameter<ICrossover> CrossoverParameter {
82      get { return (IConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
83    }
84    public IConstrainedValueParameter<IManipulator> MutatorParameter {
85      get { return (IConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
86    }
87    private IValueParameter<PercentValue> MutationProbabilityParameter {
88      get { return (IValueParameter<PercentValue>)Parameters["MutationProbability"]; }
89    }
90    private IValueParameter<IntValue> ElitesParameter {
91      get { return (IValueParameter<IntValue>)Parameters["Elites"]; }
92    }
93    private IFixedValueParameter<BoolValue> ReevaluateElitesParameter {
94      get { return (IFixedValueParameter<BoolValue>)Parameters["ReevaluateElites"]; }
95    }
96    private IValueParameter<BoolValue> PlusSelectionParameter {
97      get { return (IValueParameter<BoolValue>)Parameters["PlusSelection"]; }
98    }
99
100    private IValueParameter<EnumValue<AgingScheme>> AgingSchemeParameter {
101      get { return (IValueParameter<EnumValue<AgingScheme>>)Parameters["AgingScheme"]; }
102    }
103    private IValueParameter<IntValue> AgeGapParameter {
104      get { return (IValueParameter<IntValue>)Parameters["AgeGap"]; }
105    }
106    private IValueParameter<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 RandomCreator GlobalRandomCreator {
218      get { return (RandomCreator)OperatorGraph.InitialOperator; }
219    }
220    private SolutionsCreator SolutionsCreator {
221      get { return OperatorGraph.Iterate().OfType<SolutionsCreator>().First(); }
222    }
223    private AlpsGeneticAlgorithmMainLoop MainLoop {
224      get { return OperatorGraph.Iterate().OfType<AlpsGeneticAlgorithmMainLoop>().First(); }
225    }
226    #endregion
227
228    #region Preconfigured Analyzers
229    [Storable]
230    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
231    [Storable]
232    private BestAverageWorstQualityAnalyzer layerQualityAnalyzer;
233    [Storable]
234    private OldestAverageYoungestAgeAnalyzer ageAnalyzer;
235    [Storable]
236    private OldestAverageYoungestAgeAnalyzer layerAgeAnalyzer;
237    [Storable]
238    private AgeDistributionAnalyzer ageDistributionAnalyzer;
239    [Storable]
240    private AgeDistributionAnalyzer layerAgeDistributionAnalyzer;
241    #endregion
242
243    #region Preconfigured Terminators
244    [Storable]
245    private ComparisonTerminator<IntValue> generationsTerminator;
246    [Storable]
247    private ComparisonTerminator<IntValue> evaluationsTerminator;
248    [Storable]
249    private SingleObjectiveQualityTerminator qualityTerminator;
250    [Storable]
251    private ExecutionTimeTerminator executionTimeTerminator;
252    #endregion
253
254    #region Constructors
255    [StorableConstructor]
256    private AlpsGeneticAlgorithm(bool deserializing)
257      : base(deserializing) { }
258    [StorableHook(HookType.AfterDeserialization)]
259    private void AfterDeserialization() {
260      Initialize();
261    }
262    private AlpsGeneticAlgorithm(AlpsGeneticAlgorithm original, Cloner cloner)
263      : base(original, cloner) {
264      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
265      layerQualityAnalyzer = cloner.Clone(original.layerQualityAnalyzer);
266      ageAnalyzer = cloner.Clone(original.ageAnalyzer);
267      layerAgeAnalyzer = cloner.Clone(original.layerAgeAnalyzer);
268      ageDistributionAnalyzer = cloner.Clone(original.ageDistributionAnalyzer);
269      layerAgeDistributionAnalyzer = cloner.Clone(original.layerAgeDistributionAnalyzer);
270      generationsTerminator = cloner.Clone(original.generationsTerminator);
271      evaluationsTerminator = cloner.Clone(original.evaluationsTerminator);
272      qualityTerminator = cloner.Clone(original.qualityTerminator);
273      executionTimeTerminator = cloner.Clone(original.executionTimeTerminator);
274      Initialize();
275    }
276    public override IDeepCloneable Clone(Cloner cloner) {
277      return new AlpsGeneticAlgorithm(this, cloner);
278    }
279    public AlpsGeneticAlgorithm()
280      : base() {
281      #region Add parameters
282      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
283      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
284
285      Parameters.Add(new FixedValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the islands.", new MultiAnalyzer()));
286      Parameters.Add(new FixedValueParameter<MultiAnalyzer>("LayerAnalyzer", "The operator used to analyze each layer.", new MultiAnalyzer()));
287
288      Parameters.Add(new ValueParameter<IntValue>("NumberOfLayers", "The number of layers.", new IntValue(10)));
289      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions each layer.", new IntValue(100)));
290
291      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
292      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
293      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
294      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
295      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
296      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 });
297      Parameters.Add(new ValueParameter<BoolValue>("PlusSelection", "Include the parents in the selection of the invividuals for the next generation.", new BoolValue(false)));
298
299      Parameters.Add(new ValueParameter<EnumValue<AgingScheme>>("AgingScheme", "The aging scheme for setting the age-limits for the layers.", new EnumValue<AgingScheme>(ALPS.AgingScheme.Polynomial)));
300      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)));
301      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 });
302      Parameters.Add(new ValueParameter<IntArray>("AgeLimits", new IntArray(new int[0])) { Hidden = true });
303
304      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 });
305      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 });
306
307      Parameters.Add(new ValueParameter<MultiTerminator>("Terminator", "The termination criteria which sould be checked.", new MultiTerminator()));
308      #endregion
309
310      #region Create operators
311      var globalRandomCreator = new RandomCreator();
312      var layer0Creator = new SubScopesCreator() { Name = "Create Layer Zero" };
313      var layer0Processor = new UniformSubScopesProcessor();
314      var localRandomCreator = new LocalRandomCreator();
315      var layerVariableCreator = new VariableCreator();
316      var layerSolutionsCreator = new SolutionsCreator();
317      var initializeAgeProcessor = new UniformSubScopesProcessor();
318      var initializeAge = new VariableCreator() { Name = "Initialize Age" };
319      var initializeLayerPopulationSize = new SubScopesCounter() { Name = "Init LayerPopulationCounter" };
320      var initializeLocalEvaluatedSolutions = new Assigner() { Name = "Initialize LayerEvaluatedSolutions" };
321      var initializeGlobalEvaluatedSolutions = new DataReducer() { Name = "Initialize EvaluatedSolutions" };
322      var resultsCollector = new ResultsCollector();
323      var mainLoop = new AlpsGeneticAlgorithmMainLoop();
324      #endregion
325
326      #region Create and parameterize operator graph
327      OperatorGraph.InitialOperator = globalRandomCreator;
328
329      globalRandomCreator.RandomParameter.ActualName = "GlobalRandom";
330      globalRandomCreator.SeedParameter.Value = null;
331      globalRandomCreator.SetSeedRandomlyParameter.Value = null;
332      globalRandomCreator.Successor = layer0Creator;
333
334      layer0Creator.NumberOfSubScopesParameter.Value = new IntValue(1);
335      layer0Creator.Successor = layer0Processor;
336
337      layer0Processor.Operator = localRandomCreator;
338      layer0Processor.Successor = initializeGlobalEvaluatedSolutions;
339
340      localRandomCreator.Successor = layerVariableCreator;
341
342      layerVariableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Layer", new IntValue(0)));
343      layerVariableCreator.Successor = layerSolutionsCreator;
344
345      layerSolutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
346      layerSolutionsCreator.Successor = initializeAgeProcessor;
347
348      initializeAgeProcessor.Operator = initializeAge;
349      initializeAgeProcessor.Successor = initializeLayerPopulationSize;
350
351      initializeLayerPopulationSize.ValueParameter.ActualName = "LayerPopulationSize";
352      initializeLayerPopulationSize.Successor = initializeLocalEvaluatedSolutions;
353
354      initializeAge.CollectedValues.Add(new ValueParameter<DoubleValue>("Age", new DoubleValue(0)));
355      initializeAge.Successor = null;
356
357      initializeLocalEvaluatedSolutions.LeftSideParameter.ActualName = "LayerEvaluatedSolutions";
358      initializeLocalEvaluatedSolutions.RightSideParameter.ActualName = "LayerPopulationSize";
359      initializeLocalEvaluatedSolutions.Successor = null;
360
361      initializeGlobalEvaluatedSolutions.ReductionOperation.Value.Value = ReductionOperations.Sum;
362      initializeGlobalEvaluatedSolutions.TargetOperation.Value.Value = ReductionOperations.Assign;
363      initializeGlobalEvaluatedSolutions.ParameterToReduce.ActualName = "LayerEvaluatedSolutions";
364      initializeGlobalEvaluatedSolutions.TargetParameter.ActualName = "EvaluatedSolutions";
365      initializeGlobalEvaluatedSolutions.Successor = resultsCollector;
366
367      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
368      resultsCollector.Successor = mainLoop;
369      #endregion
370
371      #region Set selectors
372      foreach (var selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(s => !(s is IMultiObjectiveSelector)).OrderBy(s => Name))
373        SelectorParameter.ValidValues.Add(selector);
374      var defaultSelector = SelectorParameter.ValidValues.OfType<GeneralizedRankSelector>().FirstOrDefault();
375      if (defaultSelector != null) {
376        defaultSelector.PressureParameter.Value = new DoubleValue(4);
377        SelectorParameter.Value = defaultSelector;
378      }
379      #endregion
380
381      #region Create analyzers
382      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
383      layerQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
384      ageAnalyzer = new OldestAverageYoungestAgeAnalyzer();
385      layerAgeAnalyzer = new OldestAverageYoungestAgeAnalyzer();
386      ageDistributionAnalyzer = new AgeDistributionAnalyzer();
387      layerAgeDistributionAnalyzer = new AgeDistributionAnalyzer();
388      #endregion
389
390      #region Create terminators
391      generationsTerminator = new ComparisonTerminator<IntValue>("Generations", ComparisonType.Less, new IntValue(1000)) { Name = "Generations" };
392      evaluationsTerminator = new ComparisonTerminator<IntValue>("EvaluatedSolutions", ComparisonType.Less, new IntValue(int.MaxValue)) { Name = "Evaluations" };
393      qualityTerminator = new SingleObjectiveQualityTerminator() { Name = "Quality" };
394      executionTimeTerminator = new ExecutionTimeTerminator(this, new TimeSpanValue(TimeSpan.FromMinutes(5)));
395      #endregion
396
397      #region Parameterize
398      UpdateAnalyzers();
399      ParameterizeAnalyzers();
400
401      ParameterizeSelectors();
402
403      UpdateTerminators();
404
405      ParameterizeAgeLimits();
406      #endregion
407
408      Initialize();
409    }
410    #endregion
411
412    #region Events
413    public override void Prepare() {
414      if (Problem != null)
415        base.Prepare();
416    }
417    protected override void OnProblemChanged() {
418      base.OnProblemChanged();
419      ParameterizeStochasticOperator(Problem.SolutionCreator);
420      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
421      foreach (var @operator in Problem.Operators.OfType<IOperator>())
422        ParameterizeStochasticOperator(@operator);
423
424      ParameterizeIterationBasedOperators();
425
426      ParameterizeSolutionsCreator();
427      ParameterizeMainLoop();
428      ParameterizeAnalyzers();
429      ParameterizeSelectors();
430      ParameterizeTerminators();
431
432      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
433
434      UpdateAnalyzers();
435      UpdateCrossovers();
436      UpdateMutators();
437      UpdateTerminators();
438    }
439
440    protected override void RegisterProblemEvents() {
441      base.RegisterProblemEvents();
442      var maximizationParameter = (IValueParameter<BoolValue>)Problem.MaximizationParameter;
443      if (maximizationParameter != null) maximizationParameter.ValueChanged += new EventHandler(MaximizationParameter_ValueChanged);
444    }
445    protected override void DeregisterProblemEvents() {
446      var maximizationParameter = (IValueParameter<BoolValue>)Problem.MaximizationParameter;
447      if (maximizationParameter != null) maximizationParameter.ValueChanged -= new EventHandler(MaximizationParameter_ValueChanged);
448      base.DeregisterProblemEvents();
449    }
450
451    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
452      base.Problem_SolutionCreatorChanged(sender, e);
453      ParameterizeStochasticOperator(Problem.SolutionCreator);
454      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
455
456      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
457
458      ParameterizeSolutionsCreator();
459      ParameterizeAnalyzers();
460    }
461    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
462      base.Problem_EvaluatorChanged(sender, e);
463      foreach (var @operator in Problem.Operators.OfType<IOperator>())
464        ParameterizeStochasticOperator(@operator);
465
466      UpdateAnalyzers();
467
468      ParameterizeSolutionsCreator();
469      ParameterizeMainLoop();
470      ParameterizeSelectors();
471    }
472    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
473      base.Problem_OperatorsChanged(sender, e);
474      ParameterizeIterationBasedOperators();
475      UpdateCrossovers();
476      UpdateMutators();
477      UpdateTerminators();
478    }
479    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
480      ParameterizeMainLoop();
481      ParameterizeAnalyzers();
482      ParameterizeSelectors();
483    }
484    private void MaximizationParameter_ValueChanged(object sender, EventArgs e) {
485      ParameterizeTerminators();
486    }
487    private void QualityAnalyzer_CurrentBestQualityParameter_NameChanged(object sender, EventArgs e) {
488      ParameterizeTerminators();
489    }
490
491    private void AgeGapParameter_ValueChanged(object sender, EventArgs e) {
492      AgeGap.ValueChanged += AgeGap_ValueChanged;
493      ParameterizeAgeLimits();
494    }
495    private void AgeGap_ValueChanged(object sender, EventArgs e) {
496      ParameterizeAgeLimits();
497    }
498    private void AgingSchemeParameter_ValueChanged(object sender, EventArgs e) {
499      AgingScheme.ValueChanged += AgingScheme_ValueChanged;
500      ParameterizeAgeLimits();
501    }
502    private void AgingScheme_ValueChanged(object sender, EventArgs e) {
503      ParameterizeAgeLimits();
504    }
505    private void NumberOfLayersParameter_ValueChanged(object sender, EventArgs e) {
506      NumberOfLayers.ValueChanged += NumberOfLayers_ValueChanged;
507      ParameterizeAgeLimits();
508    }
509    private void NumberOfLayers_ValueChanged(object sender, EventArgs e) {
510      ParameterizeAgeLimits();
511    }
512
513    private void AnalyzerOperators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IAnalyzer>> e) {
514      foreach (var analyzer in e.Items) {
515        foreach (var parameter in analyzer.Value.Parameters.OfType<IScopeTreeLookupParameter>()) {
516          parameter.Depth = 2;
517        }
518      }
519    }
520    private void LayerAnalyzerOperators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IAnalyzer>> e) {
521      foreach (var analyzer in e.Items) {
522        IParameter resultParameter;
523        if (analyzer.Value.Parameters.TryGetValue("Results", out resultParameter)) {
524          var lookupParameter = resultParameter as ILookupParameter;
525          if (lookupParameter != null)
526            lookupParameter.ActualName = "LayerResults";
527        }
528        foreach (var parameter in analyzer.Value.Parameters.OfType<IScopeTreeLookupParameter>()) {
529          parameter.Depth = 1;
530        }
531      }
532    }
533    #endregion
534
535    #region Parameterization
536    private void Initialize() {
537      if (Problem != null)
538        Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
539
540      NumberOfLayersParameter.ValueChanged += NumberOfLayersParameter_ValueChanged;
541      NumberOfLayers.ValueChanged += NumberOfLayers_ValueChanged;
542
543      Analyzer.Operators.ItemsAdded += AnalyzerOperators_ItemsAdded;
544      LayerAnalyzer.Operators.ItemsAdded += LayerAnalyzerOperators_ItemsAdded;
545
546      AgeGapParameter.ValueChanged += AgeGapParameter_ValueChanged;
547      AgeGap.ValueChanged += AgeGap_ValueChanged;
548      AgingSchemeParameter.ValueChanged += AgingSchemeParameter_ValueChanged;
549      AgingScheme.ValueChanged += AgingScheme_ValueChanged;
550
551      qualityAnalyzer.CurrentBestQualityParameter.NameChanged += new EventHandler(QualityAnalyzer_CurrentBestQualityParameter_NameChanged);
552    }
553    private void ParameterizeSolutionsCreator() {
554      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
555      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
556    }
557    private void ParameterizeMainLoop() {
558      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
559      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
560      MainLoop.MainOperator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
561      MainLoop.MainOperator.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
562      MainLoop.MainOperator.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
563    }
564    private void ParameterizeAnalyzers() {
565      qualityAnalyzer.ResultsParameter.ActualName = "Results";
566      qualityAnalyzer.ResultsParameter.Hidden = true;
567      qualityAnalyzer.QualityParameter.Depth = 2;
568      layerQualityAnalyzer.ResultsParameter.ActualName = "LayerResults";
569      layerQualityAnalyzer.ResultsParameter.Hidden = true;
570      layerQualityAnalyzer.QualityParameter.Depth = 1;
571      if (Problem != null) {
572        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
573        qualityAnalyzer.MaximizationParameter.Hidden = true;
574        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
575        qualityAnalyzer.QualityParameter.Hidden = true;
576        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
577        qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
578        layerQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
579        layerQualityAnalyzer.MaximizationParameter.Hidden = true;
580        layerQualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
581        layerQualityAnalyzer.QualityParameter.Hidden = true;
582        layerQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
583        layerQualityAnalyzer.BestKnownQualityParameter.Hidden = true;
584      }
585    }
586    private void ParameterizeSelectors() {
587      foreach (var selector in SelectorParameter.ValidValues) {
588        selector.CopySelected = new BoolValue(true);
589        // Explicit setting of NumberOfSelectedSubScopesParameter is not required anymore because the NumberOfSelectedSubScopesCalculator calculates it itself
590        //selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSize - Elites.Value));
591        selector.NumberOfSelectedSubScopesParameter.Hidden = true;
592        ParameterizeStochasticOperatorForLayer(selector);
593      }
594      if (Problem != null) {
595        foreach (var selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
596          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
597          selector.MaximizationParameter.Hidden = true;
598          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
599          selector.QualityParameter.Hidden = true;
600        }
601      }
602    }
603    private void ParameterizeTerminators() {
604      qualityTerminator.Parameterize(qualityAnalyzer.CurrentBestQualityParameter, Problem);
605    }
606    private void ParameterizeIterationBasedOperators() {
607      if (Problem != null) {
608        foreach (var @operator in Problem.Operators.OfType<IIterationBasedOperator>()) {
609          @operator.IterationsParameter.ActualName = "Generations";
610          @operator.IterationsParameter.Hidden = true;
611          @operator.MaximumIterationsParameter.ActualName = generationsTerminator.ThresholdParameter.Name;
612          @operator.MaximumIterationsParameter.Hidden = true;
613        }
614      }
615    }
616    private void ParameterizeAgeLimits() {
617      var scheme = AgingScheme.Value;
618      int ageGap = AgeGap.Value;
619      int numberOfLayers = NumberOfLayers.Value;
620      AgeLimits = scheme.CalculateAgeLimits(ageGap, numberOfLayers);
621      AgeLimits[AgeLimits.Length - 1] = int.MaxValue; // last layer infinite age limit
622    }
623
624    private void ParameterizeStochasticOperator(IOperator @operator) {
625      var stochasticOperator = @operator as IStochasticOperator;
626      if (stochasticOperator != null) {
627        stochasticOperator.RandomParameter.ActualName = "GlobalRandom";
628        stochasticOperator.RandomParameter.Hidden = true;
629      }
630    }
631
632    private void ParameterizeStochasticOperatorForLayer(IOperator @operator) {
633      var stochasticOperator = @operator as IStochasticOperator;
634      if (stochasticOperator != null) {
635        stochasticOperator.RandomParameter.ActualName = "LocalRandom";
636        stochasticOperator.RandomParameter.Hidden = true;
637      }
638    }
639
640    #endregion
641
642    #region Updates
643    private void UpdateAnalyzers() {
644      Analyzer.Operators.Clear();
645      LayerAnalyzer.Operators.Clear();
646
647      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
648      Analyzer.Operators.Add(ageAnalyzer, ageAnalyzer.EnabledByDefault);
649      Analyzer.Operators.Add(ageDistributionAnalyzer, ageDistributionAnalyzer.EnabledByDefault);
650      LayerAnalyzer.Operators.Add(layerQualityAnalyzer, false);
651      LayerAnalyzer.Operators.Add(layerAgeAnalyzer, false);
652      LayerAnalyzer.Operators.Add(layerAgeDistributionAnalyzer, false);
653
654      if (Problem != null) {
655        foreach (var analyzer in Problem.Operators.OfType<IAnalyzer>()) {
656          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
657          LayerAnalyzer.Operators.Add((IAnalyzer)analyzer.Clone(), false);
658        }
659      }
660    }
661    private void UpdateCrossovers() {
662      var oldCrossover = CrossoverParameter.Value;
663      var defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
664      CrossoverParameter.ValidValues.Clear();
665      foreach (var crossover in Problem.Operators.OfType<ICrossover>().OrderBy(c => c.Name)) {
666        ParameterizeStochasticOperatorForLayer(crossover);
667        CrossoverParameter.ValidValues.Add(crossover);
668      }
669      if (oldCrossover != null) {
670        var crossover = CrossoverParameter.ValidValues.FirstOrDefault(c => c.GetType() == oldCrossover.GetType());
671        if (crossover != null)
672          CrossoverParameter.Value = crossover;
673        else
674          oldCrossover = null;
675      }
676      if (oldCrossover == null && defaultCrossover != null)
677        CrossoverParameter.Value = defaultCrossover;
678    }
679    private void UpdateMutators() {
680      var oldMutator = MutatorParameter.Value;
681      MutatorParameter.ValidValues.Clear();
682      foreach (var mutator in Problem.Operators.OfType<IManipulator>().OrderBy(m => m.Name)) {
683        ParameterizeStochasticOperatorForLayer(mutator);
684        MutatorParameter.ValidValues.Add(mutator);
685      }
686      if (oldMutator != null) {
687        var mutator = MutatorParameter.ValidValues.FirstOrDefault(m => m.GetType() == oldMutator.GetType());
688        if (mutator != null)
689          MutatorParameter.Value = mutator;
690      }
691    }
692    private void UpdateTerminators() {
693      var newTerminators = new Dictionary<ITerminator, bool> {
694        {generationsTerminator, !Terminators.Operators.Contains(generationsTerminator) || Terminators.Operators.ItemChecked(generationsTerminator)},
695        {evaluationsTerminator, Terminators.Operators.Contains(evaluationsTerminator) && Terminators.Operators.ItemChecked(evaluationsTerminator)},
696        {qualityTerminator, Terminators.Operators.Contains(qualityTerminator) && Terminators.Operators.ItemChecked(qualityTerminator) },
697        {executionTimeTerminator, Terminators.Operators.Contains(executionTimeTerminator) && Terminators.Operators.ItemChecked(executionTimeTerminator)}
698      };
699      if (Problem != null) {
700        foreach (var terminator in Problem.Operators.OfType<ITerminator>())
701          newTerminators.Add(terminator, !Terminators.Operators.Contains(terminator) || Terminators.Operators.ItemChecked(terminator));
702      }
703
704      Terminators.Operators.Clear();
705
706      foreach (var newTerminator in newTerminators)
707        Terminators.Operators.Add(newTerminator.Key, newTerminator.Value);
708    }
709    #endregion
710  }
711}
Note: See TracBrowser for help on using the repository browser.