Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Algorithms.ALPS/3.3/AlpsGeneticAlgorithm.cs @ 16133

Last change on this file since 16133 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

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