Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Enhanced OSALPS/HeuristicLab.Algorithms.ALPS/3.3/AlpsOs2.cs @ 15649

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

#2849: AlpsOs2 with a ContinuousMatingPoolCreator

File size: 40.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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("AlpsOs2", "An offspring selection genetic algorithm within an age-layered population structure - Version 2.")]
41  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 165)]
42  [StorableClass]
43  public class AlpsOs2 : 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 IFixedValueParameter<IntValue> SeedParameter {
58      get { return (IFixedValueParameter<IntValue>)Parameters["Seed"]; }
59    }
60    private IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
61      get { return (IFixedValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
62    }
63
64    private IFixedValueParameter<MultiAnalyzer> AnalyzerParameter {
65      get { return (IFixedValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
66    }
67    private IFixedValueParameter<MultiAnalyzer> LayerAnalyzerParameter {
68      get { return (IFixedValueParameter<MultiAnalyzer>)Parameters["LayerAnalyzer"]; }
69    }
70
71    private IFixedValueParameter<IntValue> NumberOfLayersParameter {
72      get { return (IFixedValueParameter<IntValue>)Parameters["NumberOfLayers"]; }
73    }
74    [Obsolete]
75    private IFixedValueParameter<IntValue> PopulationSizeParameter {
76      get { return (IFixedValueParameter<IntValue>)Parameters["PopulationSize"]; }
77    }
78
79    public IConstrainedValueParameter<ISelector> SelectorParameter {
80      get { return (IConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
81    }
82    public IConstrainedValueParameter<ICrossover> CrossoverParameter {
83      get { return (IConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
84    }
85    public IConstrainedValueParameter<IManipulator> MutatorParameter {
86      get { return (IConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
87    }
88    private IFixedValueParameter<PercentValue> MutationProbabilityParameter {
89      get { return (IFixedValueParameter<PercentValue>)Parameters["MutationProbability"]; }
90    }
91    private IFixedValueParameter<IntValue> ElitesParameter {
92      get { return (IFixedValueParameter<IntValue>)Parameters["Elites"]; }
93    }
94    private IFixedValueParameter<BoolValue> ReevaluateElitesParameter {
95      get { return (IFixedValueParameter<BoolValue>)Parameters["ReevaluateElites"]; }
96    }
97
98    private IFixedValueParameter<DoubleValue> SuccessRatioParameter {
99      get { return (IFixedValueParameter<DoubleValue>)Parameters["SuccessRatio"]; }
100    }
101    private IFixedValueParameter<DoubleValue> ComparisonFactorParameter {
102      get { return (IFixedValueParameter<DoubleValue>)Parameters["ComparisonFactor"]; }
103    }
104    private IFixedValueParameter<DoubleValue> MaximumSelectionPressureParameter {
105      get { return (IFixedValueParameter<DoubleValue>)Parameters["MaximumSelectionPressure"]; }
106    }
107    private IFixedValueParameter<BoolValue> OffspringSelectionBeforeMutationParameter {
108      get { return (IFixedValueParameter<BoolValue>)Parameters["OffspringSelectionBeforeMutation"]; }
109    }
110    private IFixedValueParameter<IntValue> SelectedParentsParameter {
111      get { return (IFixedValueParameter<IntValue>)Parameters["SelectedParents"]; }
112    }
113    private IFixedValueParameter<BoolValue> FillPopulationWithParentsParameter {
114      get { return (IFixedValueParameter<BoolValue>)Parameters["FillPopulationWithParents"]; }
115    }
116    [Obsolete]
117    private IFixedValueParameter<DoubleValue> TargetSelectionPressureParameter {
118      get { return (IFixedValueParameter<DoubleValue>)Parameters["TargetSelectionPressure"]; }
119    }
120
121    private IFixedValueParameter<EnumValue<AgingScheme>> AgingSchemeParameter {
122      get { return (IFixedValueParameter<EnumValue<AgingScheme>>)Parameters["AgingScheme"]; }
123    }
124    private IFixedValueParameter<IntValue> AgeGapParameter {
125      get { return (IFixedValueParameter<IntValue>)Parameters["AgeGap"]; }
126    }
127    private IFixedValueParameter<DoubleValue> AgeInheritanceParameter {
128      get { return (IFixedValueParameter<DoubleValue>)Parameters["AgeInheritance"]; }
129    }
130    private IFixedValueParameter<IntArray> AgeLimitsParameter {
131      get { return (IFixedValueParameter<IntArray>)Parameters["AgeLimits"]; }
132    }
133
134    private IFixedValueParameter<DoubleArray> MatingPoolRangesParameter {
135      get { return (IFixedValueParameter<DoubleArray>)Parameters["MatingPoolRanges"]; }
136    }
137    private IFixedValueParameter<BoolValue> ReduceToPopulationSizeParameter {
138      get { return (IFixedValueParameter<BoolValue>)Parameters["ReduceToPopulationSize"]; }
139    }
140
141    private IFixedValueParameter<MultiTerminator> TerminatorParameter {
142      get { return (IFixedValueParameter<MultiTerminator>)Parameters["Terminator"]; }
143    }
144    #endregion
145
146    #region Properties
147    public int Seed {
148      get { return SeedParameter.Value.Value; }
149      set { SeedParameter.Value.Value = value; }
150    }
151    public bool SetSeedRandomly {
152      get { return SetSeedRandomlyParameter.Value.Value; }
153      set { SetSeedRandomlyParameter.Value.Value = value; }
154    }
155
156    public MultiAnalyzer Analyzer {
157      get { return AnalyzerParameter.Value; }
158    }
159    public MultiAnalyzer LayerAnalyzer {
160      get { return LayerAnalyzerParameter.Value; }
161    }
162
163    public int NumberOfLayers {
164      get { return NumberOfLayersParameter.Value.Value; }
165      set { NumberOfLayersParameter.Value.Value = value; }
166    }
167    [Obsolete]
168    public int PopulationSize {
169      get { return PopulationSizeParameter.Value.Value; }
170      set { PopulationSizeParameter.Value.Value = value; }
171    }
172
173    public ISelector Selector {
174      get { return SelectorParameter.Value; }
175      set { SelectorParameter.Value = value; }
176    }
177    public ICrossover Crossover {
178      get { return CrossoverParameter.Value; }
179      set { CrossoverParameter.Value = value; }
180    }
181    public IManipulator Mutator {
182      get { return MutatorParameter.Value; }
183      set { MutatorParameter.Value = value; }
184    }
185    public double MutationProbability {
186      get { return MutationProbabilityParameter.Value.Value; }
187      set { MutationProbabilityParameter.Value.Value = value; }
188    }
189    public int Elites {
190      get { return ElitesParameter.Value.Value; }
191      set { ElitesParameter.Value.Value = value; }
192    }
193    public bool ReevaluteElites {
194      get { return ReevaluateElitesParameter.Value.Value; }
195      set { ReevaluateElitesParameter.Value.Value = value; }
196    }
197
198    public double SuccessRatio {
199      get { return SuccessRatioParameter.Value.Value; }
200      set { SuccessRatioParameter.Value.Value = value; }
201    }
202    public double ComparisonFactor {
203      get { return ComparisonFactorParameter.Value.Value; }
204      set { ComparisonFactorParameter.Value.Value = value; }
205    }
206    public double MaximumSelectionPressure {
207      get { return MaximumSelectionPressureParameter.Value.Value; }
208      set { MaximumSelectionPressureParameter.Value.Value = value; }
209    }
210    public bool OffspringSelectionBeforeMutation {
211      get { return OffspringSelectionBeforeMutationParameter.Value.Value; }
212      set { OffspringSelectionBeforeMutationParameter.Value.Value = value; }
213    }
214    public int SelectedParents {
215      get { return SelectedParentsParameter.Value.Value; }
216      set { SelectedParentsParameter.Value.Value = value; }
217    }
218    public bool FillPopulationWithParents {
219      get { return FillPopulationWithParentsParameter.Value.Value; }
220      set { FillPopulationWithParentsParameter.Value.Value = value; }
221    }
222    [Obsolete]
223    public double TargetSelectionPressure {
224      get { return TargetSelectionPressureParameter.Value.Value; }
225      set { TargetSelectionPressureParameter.Value.Value = value; }
226    }
227
228    public AgingScheme AgingScheme {
229      get { return AgingSchemeParameter.Value.Value; }
230      set { AgingSchemeParameter.Value.Value = value; }
231    }
232    public int AgeGap {
233      get { return AgeGapParameter.Value.Value; }
234      set { AgeGapParameter.Value.Value = value; }
235    }
236    public double AgeInheritance {
237      get { return AgeInheritanceParameter.Value.Value; }
238      set { AgeInheritanceParameter.Value.Value = value; }
239    }
240    public IntArray AgeLimits {
241      get { return AgeLimitsParameter.Value; }
242      set {
243        AgeLimits.Length = value.Length;
244        for (int i = 0; i < value.Length; i++)
245          AgeLimits[i] = value[i];
246      }
247    }
248
249    public DoubleArray MatingPoolRanges {
250      get { return MatingPoolRangesParameter.Value; }
251      set {
252        MatingPoolRanges.Length = value.Length;
253        for (int i = 0; i < value.Length; i++)
254          MatingPoolRanges[i] = value[i];
255      }
256    }
257
258    public MultiTerminator Terminators {
259      get { return TerminatorParameter.Value; }
260    }
261
262    public int MaximumGenerations {
263      get { return generationsTerminator.Threshold.Value; }
264      set { generationsTerminator.Threshold.Value = value; }
265    }
266    #endregion
267
268    #region Helper Properties
269    private SolutionsCreator SolutionsCreator {
270      get { return OperatorGraph.Iterate().OfType<SolutionsCreator>().First(); }
271    }
272    private AlpsOs2MainLoop MainLoop {
273      get { return OperatorGraph.Iterate().OfType<AlpsOs2MainLoop>().First(); }
274    }
275    #endregion
276
277    #region Preconfigured Analyzers
278    [Storable]
279    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
280    [Storable]
281    private BestAverageWorstQualityAnalyzer layerQualityAnalyzer;
282    [Storable]
283    private OldestAverageYoungestAgeAnalyzer ageAnalyzer;
284    [Storable]
285    private OldestAverageYoungestAgeAnalyzer layerAgeAnalyzer;
286    [Storable]
287    private AgeDistributionAnalyzer ageDistributionAnalyzer;
288    [Storable]
289    private AgeDistributionAnalyzer layerAgeDistributionAnalyzer;
290    [Storable]
291    private ValueAnalyzer selectionPressureAnalyzer;
292    [Storable]
293    private ValueAnalyzer layerSelectionPressureAnalyzer;
294    [Storable]
295    private ValueAnalyzer currentSuccessRatioAnalyzer;
296    #endregion
297
298    #region Preconfigured Terminators
299    [Storable]
300    private ComparisonTerminator<IntValue> generationsTerminator;
301    [Storable]
302    private ComparisonTerminator<IntValue> evaluationsTerminator;
303    [Storable]
304    private SingleObjectiveQualityTerminator qualityTerminator;
305    [Storable]
306    private ExecutionTimeTerminator executionTimeTerminator;
307    #endregion
308
309    #region Constructor, Cloning & Persistence
310    public AlpsOs2()
311      : base() {
312      #region Add parameters
313      Parameters.Add(new FixedValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
314      Parameters.Add(new FixedValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
315
316      Parameters.Add(new FixedValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze all individuals from all layers combined.", new MultiAnalyzer()));
317      Parameters.Add(new FixedValueParameter<MultiAnalyzer>("LayerAnalyzer", "The operator used to analyze each layer.", new MultiAnalyzer()));
318
319      Parameters.Add(new FixedValueParameter<IntValue>("NumberOfLayers", "The number of layers.", new IntValue(10)));
320      Parameters.Add(new FixedValueParameter<IntValue>("PopulationSize", "The size of the population of solutions in each layer.", new IntValue(100)));
321
322      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
323      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
324      Parameters.Add(new ConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
325      Parameters.Add(new FixedValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
326      Parameters.Add(new FixedValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
327      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 });
328
329      Parameters.Add(new FixedValueParameter<DoubleValue>("SuccessRatio", "The ratio of successful to total children that should be achieved.", new DoubleValue(1)));
330      Parameters.Add(new FixedValueParameter<DoubleValue>("ComparisonFactor", "The comparison factor is used to determine whether the offspring should be compared to the better parent, the worse parent or a quality value linearly interpolated between them. It is in the range [0;1].", new DoubleValue(1)));
331      Parameters.Add(new FixedValueParameter<DoubleValue>("MaximumSelectionPressure", "The maximum selection pressure that terminates the algorithm.", new DoubleValue(100)));
332      Parameters.Add(new FixedValueParameter<BoolValue>("OffspringSelectionBeforeMutation", "True if the offspring selection step should be applied before mutation, false if it should be applied after mutation.", new BoolValue(false)));
333      Parameters.Add(new FixedValueParameter<IntValue>("SelectedParents", "How much parents should be selected each time the offspring selection step is performed until the population is filled. This parameter should be about the same or twice the size of PopulationSize for smaller problems, and less for large problems.", new IntValue(200)));
334      Parameters.Add(new FixedValueParameter<BoolValue>("FillPopulationWithParents", "True if the population should be filled with parent individual or false if worse children should be used when the maximum selection pressure is exceeded.", new BoolValue(false)) { Hidden = true });
335
336      Parameters.Add(new FixedValueParameter<EnumValue<AgingScheme>>("AgingScheme", "The aging scheme for setting the age-limits for the layers.", new EnumValue<AgingScheme>(ALPS.AgingScheme.Polynomial)));
337      Parameters.Add(new FixedValueParameter<IntValue>("AgeGap", "The frequency of reseeding the lowest layer and scaling factor for the age-limits for the layers.", new IntValue(20)));
338      Parameters.Add(new FixedValueParameter<DoubleValue>("AgeInheritance", "A weight that determines the age of a child after crossover based on the older (1.0) and younger (0.0) parent.", new DoubleValue(1.0)) { Hidden = true });
339      Parameters.Add(new FixedValueParameter<IntArray>("AgeLimits", "The maximum age an individual is allowed to reach in a certain layer.", new IntArray(new int[0])) { Hidden = true });
340
341      Parameters.Add(new FixedValueParameter<DoubleArray>("MatingPoolRanges", "The range of sub-populations used for creating a mating pool. (1 = current + previous sub-population)", new DoubleArray(new[] { 1.0 })) { Hidden = true });
342      Parameters.Add(new FixedValueParameter<BoolValue>("ReduceToPopulationSize", "Reduce the CurrentPopulationSize after elder migration to PopulationSize", new BoolValue(true)) { Hidden = true });
343
344      Parameters.Add(new FixedValueParameter<MultiTerminator>("Terminator", "The termination criteria that defines if the algorithm should continue or stop.", new MultiTerminator()));
345      #endregion
346
347      #region Create operators
348      var globalRandomCreator = new RandomCreator();
349      var layer0Creator = new SubScopesCreator() { Name = "Create Layer Zero" };
350      var layer0Processor = new SubScopesProcessor();
351      var localRandomCreator = new LocalRandomCreator();
352      var layerSolutionsCreator = new SolutionsCreator();
353      var initializeAgeProcessor = new UniformSubScopesProcessor();
354      var initializeAge = new VariableCreator() { Name = "Initialize Age" };
355      var initializeCurrentPopulationSize = new SubScopesCounter() { Name = "Initialize CurrentPopulationCounter" };
356      var initializeLocalEvaluatedSolutions = new Assigner() { Name = "Initialize LayerEvaluatedSolutions" };
357      var initializeGlobalEvaluatedSolutions = new DataReducer() { Name = "Initialize EvaluatedSolutions" };
358      var resultsCollector = new ResultsCollector();
359      var mainLoop = new AlpsOs2MainLoop();
360      #endregion
361
362      #region Create and parameterize operator graph
363      OperatorGraph.InitialOperator = globalRandomCreator;
364
365      globalRandomCreator.RandomParameter.ActualName = "GlobalRandom";
366      globalRandomCreator.SeedParameter.Value = null;
367      globalRandomCreator.SeedParameter.ActualName = SeedParameter.Name;
368      globalRandomCreator.SetSeedRandomlyParameter.Value = null;
369      globalRandomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
370      globalRandomCreator.Successor = layer0Creator;
371
372      layer0Creator.NumberOfSubScopesParameter.Value = new IntValue(1);
373      layer0Creator.Successor = layer0Processor;
374
375      layer0Processor.Operators.Add(localRandomCreator);
376      layer0Processor.Successor = initializeGlobalEvaluatedSolutions;
377
378      localRandomCreator.Successor = layerSolutionsCreator;
379
380      layerSolutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
381      layerSolutionsCreator.Successor = initializeAgeProcessor;
382
383      initializeAgeProcessor.Operator = initializeAge;
384      initializeAgeProcessor.Successor = initializeCurrentPopulationSize;
385
386      initializeCurrentPopulationSize.ValueParameter.ActualName = "CurrentPopulationSize";
387      initializeCurrentPopulationSize.Successor = initializeLocalEvaluatedSolutions;
388
389      initializeAge.CollectedValues.Add(new ValueParameter<DoubleValue>("Age", new DoubleValue(0)));
390      initializeAge.Successor = null;
391
392      initializeLocalEvaluatedSolutions.LeftSideParameter.ActualName = "LayerEvaluatedSolutions";
393      initializeLocalEvaluatedSolutions.RightSideParameter.ActualName = "CurrentPopulationSize";
394      initializeLocalEvaluatedSolutions.Successor = null;
395
396      initializeGlobalEvaluatedSolutions.ReductionOperation.Value.Value = ReductionOperations.Sum;
397      initializeGlobalEvaluatedSolutions.TargetOperation.Value.Value = ReductionOperations.Assign;
398      initializeGlobalEvaluatedSolutions.ParameterToReduce.ActualName = "LayerEvaluatedSolutions";
399      initializeGlobalEvaluatedSolutions.TargetParameter.ActualName = "EvaluatedSolutions";
400      initializeGlobalEvaluatedSolutions.Successor = resultsCollector;
401
402      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
403      resultsCollector.Successor = mainLoop;
404
405      mainLoop.GlobalRandomParameter.ActualName = "GlobalRandom";
406      mainLoop.LocalRandomParameter.ActualName = localRandomCreator.LocalRandomParameter.Name;
407      mainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
408      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
409      mainLoop.LayerAnalyzerParameter.ActualName = LayerAnalyzerParameter.Name;
410      mainLoop.NumberOfLayersParameter.ActualName = NumberOfLayersParameter.Name;
411      mainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
412      mainLoop.CurrentPopulationSizeParameter.ActualName = "CurrentPopulationSize";
413      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
414      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
415      mainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
416      mainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
417      mainLoop.ElitesParameter.ActualName = ElitesParameter.Name;
418      mainLoop.ReevaluateElitesParameter.ActualName = ReevaluateElitesParameter.Name;
419      mainLoop.SuccessRatioParameter.ActualName = SuccessRatioParameter.Name;
420      mainLoop.ComparisonFactorParameter.ActualName = ComparisonFactorParameter.Name;
421      mainLoop.MaximumSelectionPressureParameter.ActualName = MaximumSelectionPressureParameter.Name;
422      mainLoop.OffspringSelectionBeforeMutationParameter.ActualName = OffspringSelectionBeforeMutationParameter.Name;
423      mainLoop.FillPopulationWithParentsParameter.ActualName = FillPopulationWithParentsParameter.Name;
424      mainLoop.AgeParameter.ActualName = "Age";
425      mainLoop.AgeGapParameter.ActualName = AgeGapParameter.Name;
426      mainLoop.AgeInheritanceParameter.ActualName = AgeInheritanceParameter.Name;
427      mainLoop.AgeLimitsParameter.ActualName = AgeLimitsParameter.Name;
428      mainLoop.MatingPoolRangesParameter.ActualName = MatingPoolRangesParameter.Name;
429      mainLoop.ReduceToPopulationSizeParameter.ActualName = ReduceToPopulationSizeParameter.Name;
430      mainLoop.TerminatorParameter.ActualName = TerminatorParameter.Name;
431      #endregion
432
433      #region Set operators
434      foreach (var selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(s => !(s is IMultiObjectiveSelector)).OrderBy(s => Name))
435        SelectorParameter.ValidValues.Add(selector);
436      var defaultSelector = SelectorParameter.ValidValues.OfType<GeneralizedRankSelector>().FirstOrDefault();
437      if (defaultSelector != null) {
438        defaultSelector.PressureParameter.Value = new DoubleValue(4.0);
439        SelectorParameter.Value = defaultSelector;
440      }
441      #endregion
442
443      #region Create analyzers
444      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
445      layerQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
446      ageAnalyzer = new OldestAverageYoungestAgeAnalyzer();
447      layerAgeAnalyzer = new OldestAverageYoungestAgeAnalyzer();
448      ageDistributionAnalyzer = new AgeDistributionAnalyzer();
449      layerAgeDistributionAnalyzer = new AgeDistributionAnalyzer();
450      selectionPressureAnalyzer = new ValueAnalyzer();
451      layerSelectionPressureAnalyzer = new ValueAnalyzer();
452      currentSuccessRatioAnalyzer = new ValueAnalyzer();
453      #endregion
454
455      #region Create terminators
456      generationsTerminator = new ComparisonTerminator<IntValue>("Generations", ComparisonType.Less, new IntValue(1000)) { Name = "Generations" };
457      evaluationsTerminator = new ComparisonTerminator<IntValue>("EvaluatedSolutions", ComparisonType.Less, new IntValue(int.MaxValue)) { Name = "Evaluations" };
458      qualityTerminator = new SingleObjectiveQualityTerminator() { Name = "Quality" };
459      executionTimeTerminator = new ExecutionTimeTerminator(this, new TimeSpanValue(TimeSpan.FromMinutes(5)));
460      #endregion
461
462      #region Parameterize
463      UpdateAnalyzers();
464      ParameterizeAnalyzers();
465
466      ParameterizeSelectors();
467
468      UpdateTerminators();
469
470      ParameterizeAgeLimits();
471      #endregion
472
473      Initialize();
474    }
475
476    private AlpsOs2(AlpsOs2 original, Cloner cloner)
477      : base(original, cloner) {
478      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
479      layerQualityAnalyzer = cloner.Clone(original.layerQualityAnalyzer);
480      ageAnalyzer = cloner.Clone(original.ageAnalyzer);
481      layerAgeAnalyzer = cloner.Clone(original.layerAgeAnalyzer);
482      ageDistributionAnalyzer = cloner.Clone(original.ageDistributionAnalyzer);
483      layerAgeDistributionAnalyzer = cloner.Clone(original.layerAgeDistributionAnalyzer);
484      selectionPressureAnalyzer = cloner.Clone(original.selectionPressureAnalyzer);
485      layerSelectionPressureAnalyzer = cloner.Clone(original.layerSelectionPressureAnalyzer);
486      currentSuccessRatioAnalyzer = cloner.Clone(original.currentSuccessRatioAnalyzer);
487      generationsTerminator = cloner.Clone(original.generationsTerminator);
488      evaluationsTerminator = cloner.Clone(original.evaluationsTerminator);
489      qualityTerminator = cloner.Clone(original.qualityTerminator);
490      executionTimeTerminator = cloner.Clone(original.executionTimeTerminator);
491      Initialize();
492    }
493    public override IDeepCloneable Clone(Cloner cloner) {
494      return new AlpsOs2(this, cloner);
495    }
496
497    [StorableConstructor]
498    private AlpsOs2(bool deserializing)
499      : base(deserializing) { }
500    [StorableHook(HookType.AfterDeserialization)]
501    private void AfterDeserialization() {
502      // BackwardsCompatibility3.3
503      #region Backwards compatible code, remove with 3.4
504      #endregion
505      Initialize();
506    }
507    #endregion
508
509    #region Events
510    public override void Prepare() {
511      if (Problem != null)
512        base.Prepare();
513    }
514    protected override void OnProblemChanged() {
515      base.OnProblemChanged();
516      ParameterizeStochasticOperator(Problem.SolutionCreator);
517      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
518      foreach (var @operator in Problem.Operators.OfType<IOperator>())
519        ParameterizeStochasticOperator(@operator);
520
521      ParameterizeIterationBasedOperators();
522
523      ParameterizeSolutionsCreator();
524      ParameterizeMainLoop();
525      ParameterizeAnalyzers();
526      ParameterizeSelectors();
527      ParameterizeTerminators();
528
529      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
530
531      UpdateAnalyzers();
532      UpdateCrossovers();
533      UpdateMutators();
534      UpdateTerminators();
535    }
536
537    protected override void RegisterProblemEvents() {
538      base.RegisterProblemEvents();
539      var maximizationParameter = (IValueParameter<BoolValue>)Problem.MaximizationParameter;
540      if (maximizationParameter != null) maximizationParameter.ValueChanged += new EventHandler(MaximizationParameter_ValueChanged);
541    }
542    protected override void DeregisterProblemEvents() {
543      var maximizationParameter = (IValueParameter<BoolValue>)Problem.MaximizationParameter;
544      if (maximizationParameter != null) maximizationParameter.ValueChanged -= new EventHandler(MaximizationParameter_ValueChanged);
545      base.DeregisterProblemEvents();
546    }
547
548    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
549      base.Problem_SolutionCreatorChanged(sender, e);
550      ParameterizeStochasticOperator(Problem.SolutionCreator);
551      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
552
553      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
554
555      ParameterizeSolutionsCreator();
556      ParameterizeAnalyzers();
557    }
558    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
559      base.Problem_EvaluatorChanged(sender, e);
560      foreach (var @operator in Problem.Operators.OfType<IOperator>())
561        ParameterizeStochasticOperator(@operator);
562
563      UpdateAnalyzers();
564
565      ParameterizeSolutionsCreator();
566      ParameterizeMainLoop();
567      ParameterizeSelectors();
568    }
569    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
570      base.Problem_OperatorsChanged(sender, e);
571      ParameterizeIterationBasedOperators();
572      UpdateCrossovers();
573      UpdateMutators();
574      UpdateTerminators();
575    }
576    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
577      ParameterizeMainLoop();
578      ParameterizeAnalyzers();
579      ParameterizeSelectors();
580    }
581    private void MaximizationParameter_ValueChanged(object sender, EventArgs e) {
582      ParameterizeTerminators();
583    }
584    private void QualityAnalyzer_CurrentBestQualityParameter_NameChanged(object sender, EventArgs e) {
585      ParameterizeTerminators();
586    }
587
588    private void AgeGap_ValueChanged(object sender, EventArgs e) {
589      ParameterizeAgeLimits();
590    }
591    private void AgingScheme_ValueChanged(object sender, EventArgs e) {
592      ParameterizeAgeLimits();
593    }
594    private void NumberOfLayers_ValueChanged(object sender, EventArgs e) {
595      ParameterizeAgeLimits();
596    }
597
598    private void AnalyzerOperators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IAnalyzer>> e) {
599      foreach (var analyzer in e.Items) {
600        foreach (var parameter in analyzer.Value.Parameters.OfType<IScopeTreeLookupParameter>()) {
601          parameter.Depth = 2;
602        }
603      }
604    }
605    private void LayerAnalyzerOperators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IAnalyzer>> e) {
606      foreach (var analyzer in e.Items) {
607        IParameter resultParameter;
608        if (analyzer.Value.Parameters.TryGetValue("Results", out resultParameter)) {
609          var lookupParameter = resultParameter as ILookupParameter;
610          if (lookupParameter != null)
611            lookupParameter.ActualName = "LayerResults";
612        }
613        foreach (var parameter in analyzer.Value.Parameters.OfType<IScopeTreeLookupParameter>()) {
614          parameter.Depth = 1;
615        }
616      }
617    }
618    #endregion
619
620    #region Parameterization
621    private void Initialize() {
622      if (Problem != null)
623        Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
624
625      NumberOfLayersParameter.Value.ValueChanged += NumberOfLayers_ValueChanged;
626
627      Analyzer.Operators.ItemsAdded += AnalyzerOperators_ItemsAdded;
628      LayerAnalyzer.Operators.ItemsAdded += LayerAnalyzerOperators_ItemsAdded;
629
630      AgeGapParameter.Value.ValueChanged += AgeGap_ValueChanged;
631      AgingSchemeParameter.Value.ValueChanged += AgingScheme_ValueChanged;
632
633      qualityAnalyzer.CurrentBestQualityParameter.NameChanged += QualityAnalyzer_CurrentBestQualityParameter_NameChanged;
634    }
635    private void ParameterizeSolutionsCreator() {
636      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
637      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
638    }
639    private void ParameterizeMainLoop() {
640      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
641      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
642      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
643    }
644    private void ParameterizeAnalyzers() {
645      qualityAnalyzer.ResultsParameter.ActualName = "Results";
646      qualityAnalyzer.ResultsParameter.Hidden = true;
647      qualityAnalyzer.QualityParameter.Depth = 2;
648      layerQualityAnalyzer.ResultsParameter.ActualName = "LayerResults";
649      layerQualityAnalyzer.ResultsParameter.Hidden = true;
650      layerQualityAnalyzer.QualityParameter.Depth = 1;
651      selectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
652      selectionPressureAnalyzer.ResultsParameter.ActualName = "Results";
653      selectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
654      selectionPressureAnalyzer.ValueParameter.Depth = 1;
655      selectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
656      layerSelectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
657      layerSelectionPressureAnalyzer.ResultsParameter.ActualName = "LayerResults";
658      layerSelectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
659      layerSelectionPressureAnalyzer.ValueParameter.Depth = 0;
660      layerSelectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
661      currentSuccessRatioAnalyzer.Name = "CurrentSuccessRatio Analyzer";
662      currentSuccessRatioAnalyzer.ResultsParameter.ActualName = "Results";
663      currentSuccessRatioAnalyzer.ValueParameter.ActualName = "CurrentSuccessRatio";
664      currentSuccessRatioAnalyzer.ValueParameter.Depth = 1;
665      currentSuccessRatioAnalyzer.ValuesParameter.ActualName = "Success Ratio History";
666      if (Problem != null) {
667        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
668        qualityAnalyzer.MaximizationParameter.Hidden = true;
669        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
670        qualityAnalyzer.QualityParameter.Hidden = true;
671        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
672        qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
673        layerQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
674        layerQualityAnalyzer.MaximizationParameter.Hidden = true;
675        layerQualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
676        layerQualityAnalyzer.QualityParameter.Hidden = true;
677        layerQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
678        layerQualityAnalyzer.BestKnownQualityParameter.Hidden = true;
679      }
680    }
681    private void ParameterizeSelectors() {
682      foreach (var selector in SelectorParameter.ValidValues) {
683        selector.CopySelected = new BoolValue(true);
684        selector.NumberOfSelectedSubScopesParameter.Hidden = true;
685        selector.NumberOfSelectedSubScopesParameter.ActualName = SelectedParentsParameter.Name;
686        ParameterizeStochasticOperatorForLayer(selector);
687      }
688      if (Problem != null) {
689        foreach (var selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
690          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
691          selector.MaximizationParameter.Hidden = true;
692          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
693          selector.QualityParameter.Hidden = true;
694        }
695      }
696    }
697    private void ParameterizeTerminators() {
698      qualityTerminator.Parameterize(qualityAnalyzer.CurrentBestQualityParameter, Problem);
699    }
700    private void ParameterizeIterationBasedOperators() {
701      if (Problem != null) {
702        foreach (var @operator in Problem.Operators.OfType<IIterationBasedOperator>()) {
703          @operator.IterationsParameter.ActualName = "Generations";
704          @operator.IterationsParameter.Hidden = true;
705          @operator.MaximumIterationsParameter.ActualName = generationsTerminator.ThresholdParameter.Name;
706          @operator.MaximumIterationsParameter.Hidden = true;
707        }
708      }
709    }
710    private void ParameterizeAgeLimits() {
711      AgeLimits = AgingScheme.CalculateAgeLimits(AgeGap, NumberOfLayers);
712    }
713
714    private void ParameterizeStochasticOperator(IOperator @operator) {
715      var stochasticOperator = @operator as IStochasticOperator;
716      if (stochasticOperator != null) {
717        stochasticOperator.RandomParameter.ActualName = "GlobalRandom";
718        stochasticOperator.RandomParameter.Hidden = true;
719      }
720    }
721
722    private void ParameterizeStochasticOperatorForLayer(IOperator @operator) {
723      var stochasticOperator = @operator as IStochasticOperator;
724      if (stochasticOperator != null) {
725        stochasticOperator.RandomParameter.ActualName = "LocalRandom";
726        stochasticOperator.RandomParameter.Hidden = true;
727      }
728    }
729    #endregion
730
731    #region Updates
732    private void UpdateAnalyzers() {
733      Analyzer.Operators.Clear();
734      LayerAnalyzer.Operators.Clear();
735
736      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
737      Analyzer.Operators.Add(ageAnalyzer, ageAnalyzer.EnabledByDefault);
738      Analyzer.Operators.Add(ageDistributionAnalyzer, ageDistributionAnalyzer.EnabledByDefault);
739      Analyzer.Operators.Add(selectionPressureAnalyzer, false);
740      selectionPressureAnalyzer.ValueParameter.Depth = 1; // Adding analyzer sets depth to 2
741      Analyzer.Operators.Add(currentSuccessRatioAnalyzer, false);
742      currentSuccessRatioAnalyzer.ValueParameter.Depth = 1; // Adding analyzer sets depth to 2
743      LayerAnalyzer.Operators.Add(layerQualityAnalyzer, false);
744      LayerAnalyzer.Operators.Add(layerAgeAnalyzer, false);
745      LayerAnalyzer.Operators.Add(layerAgeDistributionAnalyzer, false);
746      LayerAnalyzer.Operators.Add(layerSelectionPressureAnalyzer, false);
747      layerSelectionPressureAnalyzer.ValueParameter.Depth = 0; // Adding layer-analyzer sets depth to 1
748
749
750      if (Problem != null) {
751        foreach (var analyzer in Problem.Operators.OfType<IAnalyzer>()) {
752          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
753          LayerAnalyzer.Operators.Add((IAnalyzer)analyzer.Clone(), false);
754        }
755      }
756    }
757    private void UpdateCrossovers() {
758      var oldCrossover = CrossoverParameter.Value;
759      var defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
760      CrossoverParameter.ValidValues.Clear();
761      foreach (var crossover in Problem.Operators.OfType<ICrossover>().OrderBy(c => c.Name)) {
762        ParameterizeStochasticOperatorForLayer(crossover);
763        CrossoverParameter.ValidValues.Add(crossover);
764      }
765      if (oldCrossover != null) {
766        var crossover = CrossoverParameter.ValidValues.FirstOrDefault(c => c.GetType() == oldCrossover.GetType());
767        if (crossover != null)
768          CrossoverParameter.Value = crossover;
769        else
770          oldCrossover = null;
771      }
772      if (oldCrossover == null && defaultCrossover != null)
773        CrossoverParameter.Value = defaultCrossover;
774    }
775    private void UpdateMutators() {
776      IManipulator oldMutator = MutatorParameter.Value;
777      MutatorParameter.ValidValues.Clear();
778      IManipulator defaultMutator = Problem.Operators.OfType<IManipulator>().FirstOrDefault();
779
780      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name)) {
781        ParameterizeStochasticOperatorForLayer(mutator);
782        MutatorParameter.ValidValues.Add(mutator);
783      }
784
785      if (oldMutator != null) {
786        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
787        if (mutator != null) MutatorParameter.Value = mutator;
788        else oldMutator = null;
789      }
790
791      if (oldMutator == null && defaultMutator != null)
792        MutatorParameter.Value = defaultMutator;
793    }
794    private void UpdateTerminators() {
795      var newTerminators = new Dictionary<ITerminator, bool> {
796        {generationsTerminator, !Terminators.Operators.Contains(generationsTerminator) || Terminators.Operators.ItemChecked(generationsTerminator)},
797        {evaluationsTerminator, Terminators.Operators.Contains(evaluationsTerminator) && Terminators.Operators.ItemChecked(evaluationsTerminator)},
798        {qualityTerminator, Terminators.Operators.Contains(qualityTerminator) && Terminators.Operators.ItemChecked(qualityTerminator) },
799        {executionTimeTerminator, Terminators.Operators.Contains(executionTimeTerminator) && Terminators.Operators.ItemChecked(executionTimeTerminator)}
800      };
801      if (Problem != null) {
802        foreach (var terminator in Problem.Operators.OfType<ITerminator>())
803          newTerminators.Add(terminator, !Terminators.Operators.Contains(terminator) || Terminators.Operators.ItemChecked(terminator));
804      }
805
806      Terminators.Operators.Clear();
807
808      foreach (var newTerminator in newTerminators)
809        Terminators.Operators.Add(newTerminator.Key, newTerminator.Value);
810    }
811    #endregion
812  }
813}
Note: See TracBrowser for help on using the repository browser.