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

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

#2269

  • Changed default values of ALPS-GA.
  • OldestAverageYoungesAgeAnalyzer only writes the datatable to the results instead of all values.
File size: 28.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.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Operators;
30using HeuristicLab.Optimization;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.PluginInfrastructure;
35using HeuristicLab.Random;
36using HeuristicLab.Selection;
37
38namespace HeuristicLab.Algorithms.ALPS {
39  [Item("ALPS Genetic Algorithm", "A genetic algorithm with an age-layered population structure.")]
40  [Creatable("Algorithms")]
41  [StorableClass]
42  public sealed class AlpsGeneticAlgorithm : HeuristicOptimizationEngineAlgorithm, IStorableContent {
43    public string Filename { get; set; }
44
45    #region Problem Properties
46    public override Type ProblemType {
47      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
48    }
49    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
50      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
51      set { base.Problem = value; }
52    }
53    #endregion
54
55    #region Parameter Properties
56    private IValueParameter<IntValue> SeedParameter {
57      get { return (IValueParameter<IntValue>)Parameters["Seed"]; }
58    }
59    private IValueParameter<BoolValue> SetSeedRandomlyParameter {
60      get { return (IValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
61    }
62    private IValueParameter<MultiAnalyzer> AnalyzerParameter {
63      get { return (IValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
64    }
65    private IValueParameter<MultiAnalyzer> LayerAnalyzerParameter {
66      get { return (IValueParameter<MultiAnalyzer>)Parameters["LayerAnalyzer"]; }
67    }
68    private IValueParameter<IntValue> NumberOfLayersParameter {
69      get { return (IValueParameter<IntValue>)Parameters["NumberOfLayers"]; }
70    }
71    private IValueParameter<IntArray> PopulationSizeParameter {
72      get { return (IValueParameter<IntArray>)Parameters["PopulationSize"]; }
73    }
74    private IValueParameter<IntValue> MaximumGenerationsParameter {
75      get { return (IValueParameter<IntValue>)Parameters["MaximumGenerations"]; }
76    }
77    private IValueParameter<AgingScheme> AgingSchemeParameter {
78      get { return (IValueParameter<AgingScheme>)Parameters["AgingScheme"]; }
79    }
80    private IValueParameter<IntValue> AgeGapParameter {
81      get { return (IValueParameter<IntValue>)Parameters["AgeGap"]; }
82    }
83    private IValueParameter<IntArray> AgeLimitsParameter {
84      get { return (IValueParameter<IntArray>)Parameters["AgeLimits"]; }
85    }
86    private IValueParameter<ReductionOperation> AgeInheritanceParameter {
87      get { return (IValueParameter<ReductionOperation>)Parameters["AgeInheritance"]; }
88    }
89    private IValueParameter<IntValue> MatingPoolRangeParameter {
90      get { return (IValueParameter<IntValue>)Parameters["MatingPoolRange"]; }
91    }
92    private IValueParameter<PercentValue> MatingPoolSelectionPercentageParameter {
93      get { return (IValueLookupParameter<PercentValue>)Parameters["MatingPoolSelectionPercentage"]; }
94    }
95    public IConstrainedValueParameter<ISelector> SelectorParameter {
96      get { return (IConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
97    }
98    public IConstrainedValueParameter<ICrossover> CrossoverParameter {
99      get { return (IConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
100    }
101    private IValueParameter<PercentValue> MutationProbabilityParameter {
102      get { return (IValueParameter<PercentValue>)Parameters["MutationProbability"]; }
103    }
104    public IConstrainedValueParameter<IManipulator> MutatorParameter {
105      get { return (IConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
106    }
107    private IValueParameter<IntValue> ElitesParameter {
108      get { return (IValueParameter<IntValue>)Parameters["Elites"]; }
109    }
110    private IFixedValueParameter<BoolValue> ReevaluateElitesParameter {
111      get { return (IFixedValueParameter<BoolValue>)Parameters["ReevaluateElites"]; }
112    }
113    #endregion
114
115    #region Properties
116    public IntValue Seed {
117      get { return SeedParameter.Value; }
118      set { SeedParameter.Value = value; }
119    }
120    public BoolValue SetSeedRandomly {
121      get { return SetSeedRandomlyParameter.Value; }
122      set { SetSeedRandomlyParameter.Value = value; }
123    }
124    public MultiAnalyzer Analyzer {
125      get { return AnalyzerParameter.Value; }
126      set { AnalyzerParameter.Value = value; }
127    }
128    public MultiAnalyzer LayerAnalyzer {
129      get { return LayerAnalyzerParameter.Value; }
130      set { LayerAnalyzerParameter.Value = value; }
131    }
132    public IntValue NumberOfLayers {
133      get { return NumberOfLayersParameter.Value; }
134      set { NumberOfLayersParameter.Value = value; }
135    }
136
137    public IntArray PopulationSize {
138      get { return PopulationSizeParameter.Value; }
139      set { PopulationSizeParameter.Value = value; }
140    }
141    public IntValue MaximumGenerations {
142      get { return MaximumGenerationsParameter.Value; }
143      set { MaximumGenerationsParameter.Value = value; }
144    }
145    public AgingScheme AgingScheme {
146      get { return AgingSchemeParameter.Value; }
147      set { AgingSchemeParameter.Value = value; }
148    }
149    public IntValue AgeGap {
150      get { return AgeGapParameter.Value; }
151      set { AgeGapParameter.Value = value; }
152    }
153    public IntArray AgeLimits {
154      get { return AgeLimitsParameter.Value; }
155      set { AgeLimitsParameter.Value = value; }
156    }
157    public ReductionOperation AgeInheritance {
158      get { return AgeInheritanceParameter.Value; }
159      set { AgeInheritanceParameter.Value = value; }
160    }
161    public IntValue MatingPoolRange {
162      get { return MatingPoolRangeParameter.Value; }
163      set { MatingPoolRangeParameter.Value = value; }
164    }
165    public PercentValue MatingPoolSelectionPercentage {
166      get { return MatingPoolSelectionPercentageParameter.Value; }
167      set { MatingPoolSelectionPercentageParameter.Value = value; }
168    }
169    public ISelector Selector {
170      get { return SelectorParameter.Value; }
171      set { SelectorParameter.Value = value; }
172    }
173    public ICrossover Crossover {
174      get { return CrossoverParameter.Value; }
175      set { CrossoverParameter.Value = value; }
176    }
177    public PercentValue MutationProbability {
178      get { return MutationProbabilityParameter.Value; }
179      set { MutationProbabilityParameter.Value = value; }
180    }
181    public IManipulator Mutator {
182      get { return MutatorParameter.Value; }
183      set { MutatorParameter.Value = value; }
184    }
185    public IntValue Elites {
186      get { return ElitesParameter.Value; }
187      set { ElitesParameter.Value = value; }
188    }
189    public bool ReevaluteElites {
190      get { return ReevaluateElitesParameter.Value.Value; }
191      set { ReevaluateElitesParameter.Value.Value = value; }
192    }
193
194    private RandomCreator GlobalRandomCreator {
195      get { return (RandomCreator)OperatorGraph.InitialOperator; }
196    }
197    private SolutionsCreator SolutionsCreator {
198      get { return OperatorGraph.Iterate().OfType<SolutionsCreator>().First(); }
199    }
200    private AlpsGeneticAlgorithmMainLoop MainLoop {
201      get { return OperatorGraph.Iterate().OfType<AlpsGeneticAlgorithmMainLoop>().First(); }
202    }
203
204    #endregion
205
206    #region Preconfigured Analyzers
207    [Storable]
208    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
209    [Storable]
210    private BestAverageWorstQualityAnalyzer layerQualityAnalyzer;
211    #endregion
212
213    [StorableConstructor]
214    private AlpsGeneticAlgorithm(bool deserializing)
215      : base(deserializing) { }
216    private AlpsGeneticAlgorithm(AlpsGeneticAlgorithm original, Cloner cloner)
217      : base(original, cloner) {
218      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
219      layerQualityAnalyzer = cloner.Clone(original.layerQualityAnalyzer);
220      Initialize();
221    }
222    public override IDeepCloneable Clone(Cloner cloner) {
223      return new AlpsGeneticAlgorithm(this, cloner);
224    }
225    public AlpsGeneticAlgorithm()
226      : base() {
227      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
228      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
229      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the islands.", new MultiAnalyzer()));
230      Parameters.Add(new ValueParameter<MultiAnalyzer>("LayerAnalyzer", "The operator used to analyze each layer.", new MultiAnalyzer()));
231      Parameters.Add(new ValueParameter<IntValue>("NumberOfLayers", "The number of layers.", new IntValue(10)));
232      Parameters.Add(new ValueParameter<IntArray>("PopulationSize", "The size of the population of solutions each layer.", new IntArray(new[] { 100 })));
233      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations that should be processed.", new IntValue(1000)));
234      Parameters.Add(new ValueParameter<AgingScheme>("AgingScheme", "The aging scheme for setting the age-limits for the layers.", new AgingScheme(AgingSchemes.Polynomial)));
235      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)));
236      Parameters.Add(new ValueParameter<IntArray>("AgeLimits", new IntArray(new int[0])) { Hidden = true });
237      Parameters.Add(new ValueParameter<ReductionOperation>("AgeInheritance", "The operator for determining the age of an offspring based the parents' age.", new ReductionOperation(ReductionOperations.Max)) { Hidden = true });
238      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 });
239      Parameters.Add(new ValueParameter<PercentValue>("MatingPoolSelectionPercentage", "Percentage of the previous layers used for creating a mating pool.", new PercentValue(1.0, restrictToUnitInterval: true)) { Hidden = true });
240      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
241      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
242      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
243      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
244      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
245      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 });
246
247      var globalRandomCreator = new RandomCreator();
248      var layer0Creator = new SubScopesCreator() { Name = "Create Layer Zero" };
249      var layer0Processor = new LayerUniformSubScopesProcessor();
250      var localRandomCreator = new LocalRandomCreator();
251      var layerVariableCreator = new VariableCreator();
252      var layerSolutionsCreator = new SolutionsCreator();
253      var initializeAgeProcessor = new UniformSubScopesProcessor();
254      var initializeAge = new VariableCreator() { Name = "Initialize Age" };
255      var initializeLayerPopulationSize = new SubScopesCounter() { Name = "Init LayerPopulationCounter" };
256      var initializeLocalEvaluatedSolutions = new Assigner() { Name = "Initialize LayerEvaluatedSolutions" };
257      var initializeGlobalEvaluatedSolutions = new DataReducer() { Name = "Initialize EvaluatedSolutions" };
258      var resultsCollector = new ResultsCollector();
259      var mainLoop = new AlpsGeneticAlgorithmMainLoop();
260
261      OperatorGraph.InitialOperator = globalRandomCreator;
262
263      globalRandomCreator.RandomParameter.ActualName = "GlobalRandom";
264      globalRandomCreator.SeedParameter.Value = null;
265      globalRandomCreator.SetSeedRandomlyParameter.Value = null;
266      globalRandomCreator.Successor = layer0Creator;
267
268      layer0Creator.NumberOfSubScopesParameter.Value = new IntValue(1);
269      layer0Creator.Successor = layer0Processor;
270
271      layer0Processor.Operator = localRandomCreator;
272      layer0Processor.Successor = initializeGlobalEvaluatedSolutions;
273
274      localRandomCreator.Successor = layerVariableCreator;
275
276      layerVariableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Layer", new IntValue(0)));
277      //layerVariableCreator.CollectedValues.Add(new ValueParameter<ResultCollection>("Results", new ResultCollection()));
278      layerVariableCreator.Successor = layerSolutionsCreator;
279
280      layerSolutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
281      layerSolutionsCreator.Successor = initializeAgeProcessor;
282
283      initializeAgeProcessor.Operator = initializeAge;
284      initializeAgeProcessor.Successor = initializeLayerPopulationSize;
285
286      initializeLayerPopulationSize.ValueParameter.ActualName = "LayerPopulationSize";
287      initializeLayerPopulationSize.Successor = initializeLocalEvaluatedSolutions;
288
289      initializeAge.CollectedValues.Add(new ValueParameter<IntValue>("Age", new IntValue(0)));
290      initializeAge.Successor = null;
291
292      initializeLocalEvaluatedSolutions.LeftSideParameter.ActualName = "LayerEvaluatedSolutions";
293      initializeLocalEvaluatedSolutions.RightSideParameter.ActualName = "LayerPopulationSize";
294      initializeLocalEvaluatedSolutions.Successor = null;
295
296      initializeGlobalEvaluatedSolutions.ReductionOperation.Value.Value = ReductionOperations.Sum;
297      initializeGlobalEvaluatedSolutions.TargetOperation.Value.Value = ReductionOperations.Assign;
298      initializeGlobalEvaluatedSolutions.ParameterToReduce.ActualName = "LayerEvaluatedSolutions";
299      initializeGlobalEvaluatedSolutions.TargetParameter.ActualName = "EvaluatedSolutions";
300      initializeGlobalEvaluatedSolutions.Successor = resultsCollector;
301
302      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
303      resultsCollector.Successor = mainLoop;
304
305      foreach (var selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(s => !(s is IMultiObjectiveSelector)).OrderBy(s => Name))
306        SelectorParameter.ValidValues.Add(selector);
307      var porportionalSelector = SelectorParameter.ValidValues.FirstOrDefault(s => s is ProportionalSelector);
308      if (porportionalSelector != null) SelectorParameter.Value = porportionalSelector;
309
310      ParameterizeSelectors();
311
312      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
313      layerQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
314
315      RecalculateAgeLimits();
316      ParameterizeAnalyzers();
317      UpdateAnalyzers();
318
319      Initialize();
320    }
321
322    public override void Prepare() {
323      if (Problem != null)
324        base.Prepare();
325    }
326
327    #region Events
328    protected override void OnProblemChanged() {
329      ParameterizeStochasticOperator(Problem.SolutionCreator);
330      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
331      foreach (var @operator in Problem.Operators.OfType<IOperator>())
332        ParameterizeStochasticOperator(@operator);
333      ParameterizeSolutionsCreator();
334      ParameterizeMainLoop();
335      ParameterizeSelectors();
336      ParameterizeAnalyzers();
337      ParameterizeIterationBasedOperators();
338      UpdateCrossovers();
339      UpdateMutators();
340      UpdateAnalyzers();
341      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
342      base.OnProblemChanged();
343    }
344
345    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
346      ParameterizeStochasticOperator(Problem.SolutionCreator);
347      ParameterizeSolutionsCreator();
348      base.Problem_SolutionCreatorChanged(sender, e);
349    }
350    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
351      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
352      ParameterizeSolutionsCreator();
353      ParameterizeMainLoop();
354      ParameterizeSelectors();
355      ParameterizeAnalyzers();
356      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
357      base.Problem_EvaluatorChanged(sender, e);
358    }
359    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
360      foreach (var @operator in Problem.Operators.OfType<IOperator>())
361        ParameterizeStochasticOperator(@operator);
362      ParameterizeIterationBasedOperators();
363      UpdateCrossovers();
364      UpdateMutators();
365      UpdateAnalyzers();
366      base.Problem_OperatorsChanged(sender, e);
367    }
368    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
369      ParameterizeMainLoop();
370      ParameterizeSelectors();
371      ParameterizeAnalyzers();
372    }
373
374    void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
375      PopulationSizeParameter.ValueChanged += PopulationSize_ValueChanged;
376      ParameterizeSelectors();
377    }
378    void PopulationSize_ValueChanged(object sender, EventArgs e) {
379      ParameterizeSelectors();
380    }
381    void ElitesParameter_ValueChanged(object sender, EventArgs e) {
382      Elites.ValueChanged += ElitesParameter_ValueChanged;
383      ParameterizeSelectors();
384    }
385    void Elites_ValueChanged(object sender, EventArgs e) {
386      ParameterizeSelectors();
387    }
388    private void AgeGapParameter_ValueChanged(object sender, EventArgs e) {
389      AgeGap.ValueChanged += AgeGap_ValueChanged;
390      RecalculateAgeLimits();
391    }
392    private void AgeGap_ValueChanged(object sender, EventArgs e) {
393      RecalculateAgeLimits();
394    }
395    private void AgingSchemeParameter_ValueChanged(object sender, EventArgs e) {
396      AgingScheme.ValueChanged += AgingScheme_ValueChanged;
397      RecalculateAgeLimits();
398    }
399    private void AgingScheme_ValueChanged(object sender, EventArgs e) {
400      RecalculateAgeLimits();
401    }
402    private void NumberOfLayersParameter_ValueChanged(object sender, EventArgs e) {
403      NumberOfLayers.ValueChanged += NumberOfLayers_ValueChanged;
404      RecalculateAgeLimits();
405    }
406    private void NumberOfLayers_ValueChanged(object sender, EventArgs e) {
407      RecalculateAgeLimits();
408    }
409    #endregion
410
411    #region Parameterization
412    private void Initialize() {
413      PopulationSizeParameter.ValueChanged += PopulationSizeParameter_ValueChanged;
414      //PopulationSize.ValueChanged += PopulationSize_ValueChanged; TODO
415      ElitesParameter.ValueChanged += ElitesParameter_ValueChanged;
416      Elites.ValueChanged += Elites_ValueChanged;
417      if (Problem != null)
418        Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
419      AgeGapParameter.ValueChanged += AgeGapParameter_ValueChanged;
420      AgeGap.ValueChanged += AgeGap_ValueChanged;
421      AgingSchemeParameter.ValueChanged += AgingSchemeParameter_ValueChanged;
422      AgingScheme.ValueChanged += AgingScheme_ValueChanged;
423      NumberOfLayersParameter.ValueChanged += NumberOfLayersParameter_ValueChanged;
424      NumberOfLayers.ValueChanged += NumberOfLayers_ValueChanged;
425    }
426    private void ParameterizeSolutionsCreator() {
427      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
428      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
429      MainLoop.LayerUpdator.SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
430      MainLoop.LayerUpdator.SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
431    }
432    private void ParameterizeMainLoop() {
433      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
434      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
435      MainLoop.MainOperator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
436      MainLoop.MainOperator.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
437      MainLoop.MainOperator.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
438      MainLoop.EldersEmigrator.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
439      MainLoop.EldersEmigrator.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
440      MainLoop.LayerUpdator.SolutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
441    }
442    private void ParameterizeSelectors() {
443      foreach (var selector in SelectorParameter.ValidValues) {
444        selector.CopySelected = new BoolValue(true);
445        // Explicit setting of NumberOfSelectedSubScopesParameter is not required anymore because the NumberOfSelectedSubScopesCalculator calculates it itself
446        //selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSize - Elites.Value));
447        selector.NumberOfSelectedSubScopesParameter.Hidden = true;
448        ParameterizeStochasticOperatorForLayer(selector);
449      }
450      if (Problem != null) {
451        foreach (var selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
452          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
453          selector.MaximizationParameter.Hidden = true;
454          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
455          selector.QualityParameter.Hidden = true;
456        }
457      }
458    }
459    private void ParameterizeAnalyzers() {
460      qualityAnalyzer.ResultsParameter.ActualName = "Results";
461      qualityAnalyzer.ResultsParameter.Hidden = true;
462      qualityAnalyzer.QualityParameter.Depth = 2;
463      layerQualityAnalyzer.ResultsParameter.ActualName = "Results";
464      layerQualityAnalyzer.ResultsParameter.Hidden = true;
465      layerQualityAnalyzer.QualityParameter.Depth = 1;
466      if (Problem != null) {
467        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
468        qualityAnalyzer.MaximizationParameter.Hidden = true;
469        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
470        qualityAnalyzer.QualityParameter.Hidden = true;
471        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
472        qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
473        layerQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
474        layerQualityAnalyzer.MaximizationParameter.Hidden = true;
475        layerQualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
476        layerQualityAnalyzer.QualityParameter.Hidden = true;
477        layerQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
478        layerQualityAnalyzer.BestKnownQualityParameter.Hidden = true;
479      }
480    }
481    private void ParameterizeIterationBasedOperators() {
482      if (Problem != null) {
483        foreach (var @operator in Problem.Operators.OfType<IIterationBasedOperator>()) {
484          @operator.IterationsParameter.ActualName = "Generations";
485          @operator.IterationsParameter.Hidden = true;
486          @operator.MaximumIterationsParameter.ActualName = "MaximumGenerations";
487          @operator.MaximumIterationsParameter.Hidden = true;
488        }
489      }
490    }
491    private void ParameterizeStochasticOperator(IOperator @operator) {
492      var stochasticOperator = @operator as IStochasticOperator;
493      if (stochasticOperator != null) {
494        stochasticOperator.RandomParameter.ActualName = GlobalRandomCreator.RandomParameter.ActualName;
495        stochasticOperator.RandomParameter.Hidden = true;
496      }
497    }
498    private void ParameterizeStochasticOperatorForLayer(IOperator @operator) {
499      var stochasticOperator = @operator as IStochasticOperator;
500      if (stochasticOperator != null) {
501        stochasticOperator.RandomParameter.ActualName = "LocalRandom";
502        stochasticOperator.RandomParameter.Hidden = true;
503      }
504    }
505    #endregion
506
507    #region Updates
508    private void UpdateCrossovers() {
509      var oldCrossover = CrossoverParameter.Value;
510      var defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
511      CrossoverParameter.ValidValues.Clear();
512      foreach (var crossover in Problem.Operators.OfType<ICrossover>().OrderBy(c => c.Name)) {
513        ParameterizeStochasticOperatorForLayer(crossover);
514        CrossoverParameter.ValidValues.Add(crossover);
515      }
516      if (oldCrossover != null) {
517        var crossover = CrossoverParameter.ValidValues.FirstOrDefault(c => c.GetType() == oldCrossover.GetType());
518        if (crossover != null)
519          CrossoverParameter.Value = crossover;
520        else
521          oldCrossover = null;
522      }
523      if (oldCrossover == null && defaultCrossover != null)
524        CrossoverParameter.Value = defaultCrossover;
525    }
526    private void UpdateMutators() {
527      var oldMutator = MutatorParameter.Value;
528      MutatorParameter.ValidValues.Clear();
529      foreach (var mutator in Problem.Operators.OfType<IManipulator>().OrderBy(m => m.Name)) {
530        ParameterizeStochasticOperatorForLayer(mutator);
531        MutatorParameter.ValidValues.Add(mutator);
532      }
533      if (oldMutator != null) {
534        var mutator = MutatorParameter.ValidValues.FirstOrDefault(m => m.GetType() == oldMutator.GetType());
535        if (mutator != null)
536          MutatorParameter.Value = mutator;
537      }
538    }
539    private void UpdateAnalyzers() {
540      Analyzer.Operators.Clear();
541      LayerAnalyzer.Operators.Clear();
542
543      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
544      LayerAnalyzer.Operators.Add(layerQualityAnalyzer, layerQualityAnalyzer.EnabledByDefault);
545
546      if (Problem != null) {
547        foreach (var analyzer in Problem.Operators.OfType<IAnalyzer>()) {
548          foreach (var parameter in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
549            parameter.Depth = 2;
550          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
551        }
552      }
553    }
554    #endregion
555
556    #region AgeLimits calculation
557    private void RecalculateAgeLimits() {
558      IEnumerable<int> scheme;
559      switch (AgingScheme.Value) {
560        case AgingSchemes.Linear: scheme = LinearAgingScheme(); break;
561        case AgingSchemes.Fibonacci: scheme = FibonacciAgingScheme(); break;
562        case AgingSchemes.Polynomial: scheme = PolynomialAgingScheme(2); break;
563        case AgingSchemes.Exponential: scheme = ExponentialAgingScheme(2); break;
564        default: throw new NotSupportedException("Aging Scheme " + AgingScheme.Value + " is not supported.");
565      }
566
567      int ageGap = AgeGap.Value;
568      AgeLimits = new IntArray(scheme.Select(a => a * ageGap).Take(NumberOfLayers.Value).ToArray());
569    }
570
571    // 1 2 3 4 5 6 7
572    private static IEnumerable<int> LinearAgingScheme() {
573      for (int i = 0; ; i++)
574        yield return i + 1;
575    }
576    // 1 2 3 5 8 13 21
577    private static IEnumerable<int> FibonacciAgingScheme() {
578      for (int i = 1, next = 2, temp; ; temp = next, next = i + next, i = temp)
579        yield return i;
580    }
581    // (n^2): 1 2 4 9 16 25 36
582    private static IEnumerable<int> PolynomialAgingScheme(double exp) {
583      yield return 1;
584      yield return 2;
585      for (int i = 2; ; i++)
586        yield return (int)Math.Pow(i, exp);
587
588    }
589    // 1 2 4 8 16 32 64
590    private static IEnumerable<int> ExponentialAgingScheme(double @base) {
591      for (int i = 0; ; i++)
592        yield return (int)Math.Pow(@base, i);
593    }
594    #endregion
595  }
596}
Note: See TracBrowser for help on using the repository browser.