Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ALPS(old)/HeuristicLab.Algorithms.ALPS/3.3/AlpsGeneticAlgorithm.cs @ 12250

Last change on this file since 12250 was 12071, checked in by pfleck, 10 years ago

#2269

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