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

Last change on this file since 11676 was 11676, checked in by pfleck, 5 years ago

#2269 Added LayerPopulationSize variable (for PopulationSizeAnalyzer)

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