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

Last change on this file since 13117 was 13117, checked in by pfleck, 6 years ago

#2269 Added ReduceToPopulationSize parameter to control if the population is reduced to the PopulationSize after elder migration (default) or the layer can have more than PopulationSize individuals until the next generation.

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