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

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

#2269 Some small changes.

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