source: branches/IslandALPS/IslandALPS/3.3/IslandALPSAlgorithm.cs @ 13604

Last change on this file since 13604 was 13604, checked in by pkuelzer, 6 years ago

#2558 Include LayerNumber in GroupResults
Added Migration

File size: 40.0 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Security.Policy;
5using HeuristicLab.Algorithms.ALPS;
6using HeuristicLab.Analysis;
7using HeuristicLab.Collections;
8using HeuristicLab.Common;
9using HeuristicLab.Core;
10using HeuristicLab.Data;
11using HeuristicLab.Operators;
12using HeuristicLab.Optimization;
13using HeuristicLab.Optimization.Operators;
14using HeuristicLab.Parameters;
15using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
16using HeuristicLab.PluginInfrastructure;
17using HeuristicLab.Random;
18using HeuristicLab.Selection;
19
20namespace HeuristicLab.Algorithms.IslandALPS {
21  [Item("IslandALPS", "An island version of ALPS")]
22  [StorableClass]
23  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 100)]
24  public class IslandAlpsAlgorithm : HeuristicOptimizationEngineAlgorithm, IStorableContent {
25    public string Filename { get; set; }
26
27    #region Problem Properties
28
29    public override Type ProblemType {
30      get { return typeof (ISingleObjectiveHeuristicOptimizationProblem); }
31    }
32
33    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
34      get { return (ISingleObjectiveHeuristicOptimizationProblem) base.Problem; }
35      set { base.Problem = value; }
36    }
37
38    #endregion
39
40    #region Parameter Properties
41
42    #region ALPSParameter
43    private IValueParameter<IntValue> AgeGapParameter {
44      get { return (IValueParameter<IntValue>) Parameters["AgeGap"]; }
45    }
46    private IValueParameter<EnumValue<AgingScheme>> AgingSchemeParameter {
47      get { return (IValueParameter<EnumValue<AgingScheme>>)Parameters["AgingScheme"]; }
48    }
49    private IValueParameter<DoubleValue> AgeInheritanceParameter {
50      get { return (IValueParameter<DoubleValue>) Parameters["AgeInheritance"]; }
51    }
52    private IValueParameter<IntArray> AgeLimitsParameter {
53      get { return (IValueParameter<IntArray>) Parameters["AgeLimits"]; }
54    }
55    private IValueParameter<BoolValue> ReduceToPopulationSizeParameter {
56      get { return (IValueParameter<BoolValue>) Parameters["ReduceToPopulationSize"]; }
57    }
58    private IValueParameter<IntValue> NumberOfLayersParameter {
59      get { return (IValueParameter<IntValue>) Parameters["NumberOfLayers"]; }
60    }
61    private IValueParameter<MultiAnalyzer> LayerAnalyzerParameter {
62      get { return (IValueParameter<MultiAnalyzer>)Parameters["LayerAnalyzer"]; }
63    }
64    private IValueParameter<MultiAnalyzer> GroupAnalyzerParameter {
65      get { return (IValueParameter<MultiAnalyzer>)Parameters["GroupAnalyzer"]; }
66    }
67    private IValueParameter<BoolValue> PlusSelectionParameter {
68      get { return (IValueParameter<BoolValue>)Parameters["PlusSelection"]; }
69    }
70    #endregion
71
72    #region IslandParameter
73    private IValueParameter<MultiAnalyzer> IslandAnalyzerParameter {
74      get { return (IValueParameter<MultiAnalyzer>) Parameters["IslandAnalyzer"]; }
75    }
76    private IValueParameter<IntValue> NumberOfIslandsParameter {
77      get { return (IValueParameter<IntValue>) Parameters["NumberOfIslands"]; }
78    }
79    private IValueParameter<PercentValue> MigrationRateParameter {
80      get { return (IValueParameter<PercentValue>)Parameters["MigrationRate"]; }
81    }
82    private IValueParameter<IntValue> MigrationIntervalParameter {
83      get { return (IValueParameter<IntValue>)Parameters["MigrationInterval"]; }
84    }
85    public IConstrainedValueParameter<IMigrator> MigratorParameter {
86      get { return (IConstrainedValueParameter<IMigrator>)Parameters["Migrator"]; }
87    }
88    public IConstrainedValueParameter<ISelector> EmigrantsSelectorParameter {
89      get { return (IConstrainedValueParameter<ISelector>)Parameters["EmigrantsSelector"]; }
90    }
91    public IConstrainedValueParameter<IReplacer> ImmigrationReplacerParameter {
92      get { return (IConstrainedValueParameter<IReplacer>)Parameters["ImmigrationReplacer"]; }
93    }
94    #endregion
95
96    #region GeneralParameter
97    private IValueParameter<IntValue> SeedParameter {
98      get { return (IValueParameter<IntValue>) Parameters["Seed"]; }
99    }
100    private IValueParameter<BoolValue> SetSeedRandomlyParameter {
101      get { return (IValueParameter<BoolValue>) Parameters["SetSeedRandomly"]; }
102    }
103    private IValueParameter<IntValue> PopulationSizeParameter {
104      get { return (IValueParameter<IntValue>) Parameters["PopulationSize"]; }
105    }
106    private IValueParameter<MultiAnalyzer> AnalyzerParameter {
107      get { return (IValueParameter<MultiAnalyzer>) Parameters["Analyzer"]; }
108    }
109    public IConstrainedValueParameter<ISelector> SelectorParameter {
110      get { return (IConstrainedValueParameter<ISelector>) Parameters["Selector"]; }
111    }
112    public IConstrainedValueParameter<ICrossover> CrossoverParameter {
113      get { return (IConstrainedValueParameter<ICrossover>) Parameters["Crossover"]; }
114    }
115    private IValueParameter<PercentValue> MutationProbabilityParameter {
116      get { return (IValueParameter<PercentValue>) Parameters["MutationProbability"]; }
117    }
118    public IConstrainedValueParameter<IManipulator> MutatorParameter {
119      get { return (IConstrainedValueParameter<IManipulator>) Parameters["Mutator"]; }
120    }
121    private IValueParameter<IntValue> ElitesParameter {
122      get { return (IValueParameter<IntValue>) Parameters["Elites"]; }
123    }
124    private IFixedValueParameter<BoolValue> ReevaluateElitesParameter {
125      get { return (IFixedValueParameter<BoolValue>) Parameters["ReevaluateElites"]; }
126    }
127    private IValueParameter<MultiTerminator> TerminatorParameter {
128      get { return (IValueParameter<MultiTerminator>) Parameters["Terminator"]; }
129    }
130    #endregion
131    #endregion
132
133    #region Properties
134    public IntValue Seed {
135      get { return SeedParameter.Value; }
136      set { SeedParameter.Value = value; }
137    }
138    public BoolValue SetSeedRandomly {
139      get { return SetSeedRandomlyParameter.Value; }
140      set { SetSeedRandomlyParameter.Value = value; }
141    }
142    public IntValue PopulationSize {
143      get { return PopulationSizeParameter.Value; }
144      set { PopulationSizeParameter.Value = value; }
145    }
146    public IntValue NumberOfIslands {
147      get { return NumberOfIslandsParameter.Value; }
148      set { NumberOfIslandsParameter.Value = value; }
149    }
150    public MultiAnalyzer Analyzer {
151      get { return AnalyzerParameter.Value; }
152      set { AnalyzerParameter.Value = value; }
153    }
154    public MultiAnalyzer IslandAnalyzer {
155      get { return IslandAnalyzerParameter.Value; }
156      set { IslandAnalyzerParameter.Value = value; }
157    }
158    public MultiAnalyzer LayerAnalyzer {
159      get { return LayerAnalyzerParameter.Value; }
160      set { LayerAnalyzerParameter.Value = value; }
161    }
162    public MultiAnalyzer GroupAnalyzer {
163      get { return GroupAnalyzerParameter.Value; }
164      set { GroupAnalyzerParameter.Value = value; }
165    }
166    public ISelector Selector {
167      get { return SelectorParameter.Value; }
168      set { SelectorParameter.Value = value; }
169    }
170    public ICrossover Crossover {
171      get { return CrossoverParameter.Value; }
172      set { CrossoverParameter.Value = value; }
173    }
174    public PercentValue MutationProbability {
175      get { return MutationProbabilityParameter.Value; }
176      set { MutationProbabilityParameter.Value = value; }
177    }
178    public IManipulator Mutator {
179      get { return MutatorParameter.Value; }
180      set { MutatorParameter.Value = value; }
181    }
182    public IntValue Elites {
183      get { return ElitesParameter.Value; }
184      set { ElitesParameter.Value = value; }
185    }
186    public bool ReevaluteElites {
187      get { return ReevaluateElitesParameter.Value.Value; }
188      set { ReevaluateElitesParameter.Value.Value = value; }
189    }
190    public MultiTerminator Terminators {
191      get { return TerminatorParameter.Value; }
192    }
193    public EnumValue<AgingScheme> AgingScheme {
194      get { return AgingSchemeParameter.Value; }
195      set { AgingSchemeParameter.Value = value; }
196    }
197    public IntValue AgeGap {
198      get { return AgeGapParameter.Value; }
199      set { AgeGapParameter.Value = value; }
200    }
201    public DoubleValue AgeInheritance {
202      get { return AgeInheritanceParameter.Value; }
203      set { AgeInheritanceParameter.Value = value; }
204    }
205    public IntArray AgeLimits {
206      get { return AgeLimitsParameter.Value; }
207      set { AgeLimitsParameter.Value = value; }
208    }
209    public IntValue NumberOfLayers {
210      get { return NumberOfLayersParameter.Value; }
211      set { NumberOfLayersParameter.Value = value; }
212    }
213    #endregion
214
215    #region Helper Properties
216
217    private IslandAlpsAlgorthmsMainLoop MainLoop {
218      get { return OperatorGraph.Iterate().OfType<IslandAlpsAlgorthmsMainLoop>().First(); }
219    }
220
221    private SolutionsCreator SolutionsCreator {
222      get { return OperatorGraph.Iterate().OfType<SolutionsCreator>().First(); }
223    }
224
225    #endregion
226
227    #region Preconfigured Terminators
228
229    [Storable] private readonly ComparisonTerminator<IntValue> generationsTerminator;
230    [Storable] private readonly ComparisonTerminator<IntValue> evaluationsTerminator;
231    [Storable] private readonly SingleObjectiveQualityTerminator qualityTerminator;
232    [Storable] private readonly ExecutionTimeTerminator executionTimeTerminator;
233
234    #endregion
235
236    #region Preconfigured Analyzers
237
238    [Storable] private readonly BestAverageWorstQualityAnalyzer qualityAnalyzer;
239    [Storable] private readonly BestAverageWorstQualityAnalyzer islandQualityAnalyzer;
240    [Storable] private readonly BestAverageWorstQualityAnalyzer layerQualityAnalyzer;
241    [Storable] private readonly BestAverageWorstQualityAnalyzer groupQualityAnalyzer;
242
243    #endregion
244
245    #region Constructors
246
247    [StorableConstructor]
248    private IslandAlpsAlgorithm(bool deserializing) : base(deserializing) {
249    }
250
251    [StorableHook(HookType.AfterDeserialization)]
252    private void AfterDeserialization() {
253      InitializeEventHandler();
254    }
255
256    private IslandAlpsAlgorithm(IslandAlpsAlgorithm original, Cloner cloner)
257      : base(original, cloner) {
258      //clone Properties
259
260      //analyzer
261      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
262      islandQualityAnalyzer = cloner.Clone(original.islandQualityAnalyzer);
263      layerQualityAnalyzer = cloner.Clone(original.layerQualityAnalyzer);
264      groupQualityAnalyzer = cloner.Clone(original.groupQualityAnalyzer);
265      //terminator
266      generationsTerminator = cloner.Clone(original.generationsTerminator);
267      evaluationsTerminator = cloner.Clone(original.evaluationsTerminator);
268      qualityTerminator = cloner.Clone(original.qualityTerminator);
269      executionTimeTerminator = cloner.Clone(original.executionTimeTerminator);
270
271      InitializeEventHandler();
272    }
273
274    public IslandAlpsAlgorithm() {
275      #region add Parameter
276      #region ALPSParameter
277      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)));
278      Parameters.Add(new ValueParameter<DoubleValue>("AgeInheritance", "A weight that determines the age of a child after crossover based on the older (1.0) and younger (0.0) parent.", new DoubleValue(0.5)));
279      Parameters.Add(new ValueParameter<IntArray>("AgeLimits", "The maximum age an individual is allowed to reach in a certain layer.", new IntArray(new int[0])) { Hidden = true });
280      Parameters.Add(new ValueParameter<EnumValue<AgingScheme>>("AgingScheme", "The aging scheme for setting the age-limits for the layers.", new EnumValue<AgingScheme>(ALPS.AgingScheme.Polynomial)));
281      Parameters.Add(new ValueParameter<BoolValue>("ReduceToPopulationSize", ".", new BoolValue(true)));
282
283      Parameters.Add(new ValueParameter<IntValue>("NumberOfLayers", "", new IntValue(10)));
284      Parameters.Add(new ValueParameter<MultiAnalyzer>("LayerAnalyzer", "The operator used to analyze each layer.", new MultiAnalyzer()));
285      Parameters.Add(new ValueParameter<MultiAnalyzer>("GroupAnalyzer", "The operator used to analyze each layergroup.", new MultiAnalyzer()));
286      Parameters.Add(new ValueParameter<BoolValue>("PlusSelection", "Include the parents in the selection of the invividuals for the next generation.", new BoolValue(false)));
287
288      #endregion
289      #region IslandParameter
290      Parameters.Add(new ValueParameter<IntValue>("NumberOfIslands", "The number of islands.", new IntValue(5)));
291      Parameters.Add(new ValueParameter<PercentValue>("MigrationRate", "How many individuals should migrate.", new PercentValue(0.15)));
292      Parameters.Add(new ValueParameter<IntValue>("MigrationInterval", "The number Generations before a migration occurs.", new IntValue(20)));
293      Parameters.Add(new ValueParameter<MultiAnalyzer>("IslandAnalyzer", "The operator used to analyze each island.", new MultiAnalyzer()));
294      Parameters.Add(new ConstrainedValueParameter<IMigrator>("Migrator", "The migration strategy."));
295      Parameters.Add(new ConstrainedValueParameter<ISelector>("EmigrantsSelector", "Selects the individuals that will be migrated."));
296      Parameters.Add(new ConstrainedValueParameter<IReplacer>("ImmigrationReplacer", "Selects the population from the unification of the original population and the immigrants."));
297
298      #endregion
299      #region GeneralParameter   
300      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
301      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
302      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions.", new IntValue(100)));
303      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the islands.", new MultiAnalyzer()));
304      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
305      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
306      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
307      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
308      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
309      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 });
310      Parameters.Add(new ValueParameter<MultiTerminator>("Terminator", "The termination criteria that defines if the algorithm should continue or stop.", new MultiTerminator()));
311      #endregion
312
313      #endregion
314
315      #region create Operators
316
317      var globalRandomCreator = new RandomCreator();
318      var islandLayerCreator = new SubScopesCreator {Name = "Create Islands"};
319      var islandUssp = new UniformSubScopesProcessor();
320      var islandRandomCreator = new LocalRandomCreator();
321      var layerZeroCreator = new SubScopesCreator {Name = "Create Layer 0"};
322      var layerZeroUssp = new UniformSubScopesProcessor();
323      var layerRandomCreator = new LocalRandomCreator();
324      var islandSolutionsCounter = new DataReducer {Name = "Count IslandSolutions"};
325      var layerSolutionCreator = new SolutionsCreator();
326      var ageInitializerUssp = new UniformSubScopesProcessor();
327      var ageInitializerVc = new VariableCreator {Name = "Initialize Age"};
328      var evaluatedSolutionsVc = new VariableCreator {Name = "Create LayerEvaluatedSolutions"};
329      var evaluatedSolutionsCounter = new SubScopesCounter {Name = "Count LayerEvaluatedSolutions"};
330      var globalEvaluatedSolutionsCounter = new DataReducer {Name = "Count GlobalSolutions"};
331      var resultsCollector = new ResultsCollector();
332      var mainLoop = new IslandAlpsAlgorthmsMainLoop();
333
334      #endregion
335
336      #region Set selectors
337
338      var selectors = ApplicationManager.Manager.GetInstances<ISelector>()
339                                        .Where(s => !(s is IMultiObjectiveSelector))
340                                        .OrderBy(s => Name);
341      foreach (var selector in selectors)
342        SelectorParameter.ValidValues.Add(selector);
343
344      var defaultSelector = SelectorParameter.ValidValues.OfType<GeneralizedRankSelector>().FirstOrDefault();
345      if (defaultSelector != null) {
346        defaultSelector.PressureParameter.Value = new DoubleValue(4.0);
347        SelectorParameter.Value = defaultSelector;
348      }
349
350      #endregion
351
352      #region Create Analyzers
353
354      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
355      islandQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
356      layerQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
357      groupQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
358      #endregion
359
360      #region Create terminators
361
362      generationsTerminator = new ComparisonTerminator<IntValue>("Generations", ComparisonType.Less, new IntValue(1000)) {
363        Name = "Generations"
364      };
365      evaluationsTerminator = new ComparisonTerminator<IntValue>("EvaluatedSolutions", ComparisonType.Less,
366        new IntValue(int.MaxValue)) {Name = "Evaluations"};
367      qualityTerminator = new SingleObjectiveQualityTerminator {Name = "Quality"};
368      executionTimeTerminator = new ExecutionTimeTerminator(this, new TimeSpanValue(TimeSpan.FromMinutes(5)));
369
370      #endregion
371
372      #region Operator Graph
373
374      globalRandomCreator.RandomParameter.ActualName = "GlobalRandom";
375      globalRandomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
376      globalRandomCreator.SetSeedRandomlyParameter.Value = null;
377      globalRandomCreator.SeedParameter.ActualName = SeedParameter.Name;
378      globalRandomCreator.SeedParameter.Value = null;
379
380      //create islands
381      islandLayerCreator.NumberOfSubScopesParameter.ActualName = NumberOfIslandsParameter.Name;
382
383      islandRandomCreator.GlobalRandomParameter.ActualName = globalRandomCreator.RandomParameter.ActualName;
384      islandRandomCreator.LocalRandomParameter.ActualName = "IslandRandom";
385
386      layerZeroCreator.NumberOfSubScopesParameter.Value = new IntValue(1);
387
388      islandSolutionsCounter.ParameterToReduce.Depth = 1;
389      islandSolutionsCounter.ParameterToReduce.ActualName = "LayerEvaluatedSolutions";
390      islandSolutionsCounter.TargetParameter.ActualName = "IslandEvaluatedSolutions";
391      islandSolutionsCounter.ReductionOperation.Value.Value = ReductionOperations.Sum;
392      islandSolutionsCounter.TargetOperation.Value.Value = ReductionOperations.Assign;
393
394      layerRandomCreator.GlobalRandomParameter.ActualName = globalRandomCreator.RandomParameter.ActualName;
395      layerRandomCreator.LocalRandomParameter.ActualName = "LayerRandom";
396
397      layerSolutionCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
398      layerSolutionCreator.ParallelParameter.Value = new BoolValue(true);
399
400      ageInitializerVc.CollectedValues.Add(new ValueParameter<DoubleValue>("Age", new DoubleValue(0)));
401
402      evaluatedSolutionsVc.CollectedValues.Add(new ValueParameter<IntValue>("LayerEvaluatedSolutions", new IntValue(0)));
403
404      evaluatedSolutionsCounter.ValueParameter.ActualName = "LayerEvaluatedSolutions";
405
406      globalEvaluatedSolutionsCounter.ParameterToReduce.Depth = 1;
407      globalEvaluatedSolutionsCounter.ParameterToReduce.ActualName = "IslandEvaluatedSolutions";
408      globalEvaluatedSolutionsCounter.TargetParameter.ActualName = "EvaluatedSolutions";
409      globalEvaluatedSolutionsCounter.ReductionOperation.Value.Value = ReductionOperations.Sum;
410      globalEvaluatedSolutionsCounter.TargetOperation.Value.Value = ReductionOperations.Assign;
411
412      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("EvaluatedSolutions"));
413
414      //flow
415      OperatorGraph.InitialOperator = globalRandomCreator;
416      globalRandomCreator.Successor = islandLayerCreator;
417      islandLayerCreator.Successor = islandUssp;
418      islandUssp.Operator = islandRandomCreator;
419      islandRandomCreator.Successor = layerZeroCreator;
420      layerZeroCreator.Successor = layerZeroUssp;
421      layerZeroUssp.Operator = layerRandomCreator;
422      layerRandomCreator.Successor = layerSolutionCreator;
423      layerSolutionCreator.Successor = ageInitializerUssp;
424      ageInitializerUssp.Operator = ageInitializerVc;
425      ageInitializerVc.Successor = null;
426      ageInitializerUssp.Successor = evaluatedSolutionsVc;
427      evaluatedSolutionsVc.Successor = evaluatedSolutionsCounter;
428      evaluatedSolutionsCounter.Successor = null;
429      layerZeroUssp.Successor = islandSolutionsCounter;
430      islandSolutionsCounter.Successor = null;
431      islandUssp.Successor = globalEvaluatedSolutionsCounter;
432      globalEvaluatedSolutionsCounter.Successor = resultsCollector;
433      resultsCollector.Successor = mainLoop;
434     
435      #endregion
436      #region parametrize
437      ParameterizeAnalyzers();
438      UpdateAnalyzers();
439      ParameterizeSelectors();
440      UpdateTerminators();
441      ParameterizeAgeLimits();
442      ParametrizeMigration();
443      #endregion
444
445      InitializeEventHandler();
446    }
447
448
449    public override IDeepCloneable Clone(Cloner cloner) {
450      return new IslandAlpsAlgorithm(this, cloner);
451    }
452
453    #endregion
454
455    #region events
456
457    protected override void OnProblemChanged() {
458      base.OnProblemChanged();
459      ParameterizeStochasticOperator(Problem.SolutionCreator);
460      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
461      foreach (var op in Problem.Operators.OfType<IOperator>()) {
462        ParameterizeStochasticOperator(op);
463      }
464
465      ParameterizeSolutionsCreator();
466      ParameterizeMainLoop();
467      ParameterizeSelectors();
468      ParameterizeAnalyzers();
469      ParameterizeIterationBasedOperators();
470
471      UpdateAnalyzers();
472      UpdateCrossovers();
473      UpdateMutators();
474      UpdateTerminators();
475    }
476
477    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
478      base.Problem_SolutionCreatorChanged(sender, e);
479      ParameterizeStochasticOperator(Problem.SolutionCreator);
480      ParameterizeSolutionsCreator();
481    }
482
483    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
484      base.Problem_EvaluatorChanged(sender, e);
485
486      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
487      ParameterizeSolutionsCreator();
488      ParameterizeMainLoop();
489      ParameterizeSelectors();
490      ParameterizeAnalyzers();
491      ParameterizeTerminators();
492
493      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
494
495      UpdateAnalyzers();
496      UpdateCrossovers();
497      UpdateMutators();
498      UpdateTerminators();
499    }
500
501    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
502      base.Problem_OperatorsChanged(sender, e);
503      UpdateAnalyzers();
504      UpdateTerminators();
505    }
506
507    #endregion
508
509    #region Update Functions
510
511    private void UpdateCrossovers() {
512      var oldCrossover = CrossoverParameter.Value;
513      var defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
514      CrossoverParameter.ValidValues.Clear();
515      foreach (var crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name)) {
516        ParameterizeStochasticOperatorForLayer(crossover);
517        CrossoverParameter.ValidValues.Add(crossover);
518      }
519      if (oldCrossover != null) {
520        var crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
521        if (crossover != null) CrossoverParameter.Value = crossover;
522        else oldCrossover = null;
523      }
524      if (oldCrossover == null && defaultCrossover != null)
525        CrossoverParameter.Value = defaultCrossover;
526    }
527
528    private void UpdateMutators() {
529      var oldMutator = MutatorParameter.Value;
530      MutatorParameter.ValidValues.Clear();
531      foreach (var mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name)) {
532        ParameterizeStochasticOperatorForLayer(mutator);
533        MutatorParameter.ValidValues.Add(mutator);
534      }
535      if (oldMutator != null) {
536        var mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
537        if (mutator != null) MutatorParameter.Value = mutator;
538      }
539    }
540
541    private void UpdateAnalyzers() {
542      LayerAnalyzer.Operators.Clear();
543      IslandAnalyzer.Operators.Clear();
544      GroupAnalyzer.Operators.Clear();
545      Analyzer.Operators.Clear();
546
547      //add analyzer
548      GroupAnalyzer.Operators.Add(groupQualityAnalyzer, groupQualityAnalyzer.EnabledByDefault);
549      LayerAnalyzer.Operators.Add(layerQualityAnalyzer, layerQualityAnalyzer.EnabledByDefault);
550      IslandAnalyzer.Operators.Add(islandQualityAnalyzer, islandQualityAnalyzer.EnabledByDefault);
551      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
552      //depth for each analyzer gets set when added
553      if (Problem != null) {
554        foreach (var analyzer in Problem.Operators.OfType<IAnalyzer>()) {
555          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
556          IslandAnalyzer.Operators.Add((IAnalyzer)analyzer.Clone(),false);
557          LayerAnalyzer.Operators.Add((IAnalyzer)analyzer.Clone(), false);
558          GroupAnalyzer.Operators.Add((IAnalyzer) analyzer.Clone(),false);
559        }
560      }
561    }
562
563    private void UpdateTerminators() {
564      var newTerminators = new Dictionary<ITerminator, bool> {
565        {
566          generationsTerminator,
567          !Terminators.Operators.Contains(generationsTerminator) ||
568          Terminators.Operators.ItemChecked(generationsTerminator)
569        }, {
570          evaluationsTerminator,
571          Terminators.Operators.Contains(evaluationsTerminator) &&
572          Terminators.Operators.ItemChecked(evaluationsTerminator)
573        }, {
574          qualityTerminator,
575          Terminators.Operators.Contains(qualityTerminator) && Terminators.Operators.ItemChecked(qualityTerminator)
576        }, {
577          executionTimeTerminator,
578          Terminators.Operators.Contains(executionTimeTerminator) &&
579          Terminators.Operators.ItemChecked(executionTimeTerminator)
580        }
581      };
582      if (Problem != null) {
583        foreach (var terminator in Problem.Operators.OfType<ITerminator>())
584          newTerminators.Add(terminator,
585            !Terminators.Operators.Contains(terminator) || Terminators.Operators.ItemChecked(terminator));
586      }
587
588      Terminators.Operators.Clear();
589
590      foreach (var newTerminator in newTerminators)
591        Terminators.Operators.Add(newTerminator.Key, newTerminator.Value);
592    }
593
594    private void InitializeEventHandler() {
595      PopulationSizeParameter.ValueChanged += PopulationSizeParameter_ValueChanged;
596      PopulationSize.ValueChanged += PopulationSize_ValueChanged;
597      ElitesParameter.ValueChanged += ElitesParameter_ValueChanged;
598      Elites.ValueChanged += Elites_ValueChanged;
599      MigrationRateParameter.Value.ValueChanged += MigrationRate_ValueChanged;
600      MigrationRateParameter.ValueChanged += MigrationRate_ValueChanged;
601
602      Analyzer.Operators.ItemsAdded += AnalyzerOperators_ItemsAdded;
603      IslandAnalyzer.Operators.ItemsAdded += IslandAnalyzerOperators_ItemsAdded;
604      LayerAnalyzer.Operators.ItemsAdded += LayerAnalyzerOperators_ItemsAdded;
605      GroupAnalyzer.Operators.ItemsAdded += GroupAnalyzerOperators_ItemsAdded;
606
607      if (Problem != null) {
608        Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
609      }
610
611      AgeGapParameter.ValueChanged += AgeGapParameter_ValueChanged;
612      AgeGap.ValueChanged += AgeGap_ValueChanged;
613      AgingSchemeParameter.ValueChanged += AgingSchemeParameter_ValueChanged;
614      AgingScheme.ValueChanged += AgingScheme_ValueChanged;
615
616      NumberOfLayersParameter.ValueChanged += NumberOfLayersParameter_ValueChanged;
617      NumberOfLayers.ValueChanged += NumberOfLayers_ValueChanged;
618
619    }
620
621    private void MigrationRate_ValueChanged(object sender, EventArgs e) {
622      var migrationSize = (int)Math.Ceiling(MigrationRateParameter.Value.Value * PopulationSize.Value);
623      foreach (var selector in EmigrantsSelectorParameter.ValidValues) {
624        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(migrationSize);
625      }
626    }
627
628    private void GroupAnalyzerOperators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IAnalyzer>> e) {
629      foreach (var analyzer in e.Items) {
630        IParameter resultParameter;
631        if (analyzer.Value.Parameters.TryGetValue("Results", out resultParameter)) {
632          var lookupParameter = resultParameter as ILookupParameter;
633          if (lookupParameter != null)
634            lookupParameter.ActualName = "GroupResults";
635        }
636        foreach (var parameter in analyzer.Value.Parameters.OfType<IScopeTreeLookupParameter>()) {
637          parameter.Depth = 1;
638        }
639      }
640    }
641
642    private void IslandAnalyzerOperators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IAnalyzer>> e) {
643      foreach (var analyzer in e.Items) {
644        IParameter resultParameter;
645        if (analyzer.Value.Parameters.TryGetValue("Results", out resultParameter)) {
646          var lookupParameter = resultParameter as ILookupParameter;
647          if (lookupParameter != null)
648            lookupParameter.ActualName = "IslandResults";
649        }
650        foreach (var parameter in analyzer.Value.Parameters.OfType<IScopeTreeLookupParameter>()) {
651          parameter.Depth = 2;
652        }
653      }
654    }
655    private void LayerAnalyzerOperators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IAnalyzer>> e) {
656      foreach (var analyzer in e.Items) {
657        IParameter resultParameter;
658        if (analyzer.Value.Parameters.TryGetValue("Results", out resultParameter)) {
659          var lookupParameter = resultParameter as ILookupParameter;
660          if (lookupParameter != null)
661            lookupParameter.ActualName = "LayerResults";
662        }
663        foreach (var parameter in analyzer.Value.Parameters.OfType<IScopeTreeLookupParameter>()) {
664          parameter.Depth = 1;
665        }
666      }
667    }
668
669    private void AnalyzerOperators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IAnalyzer>> e) {
670      foreach (var analyzer in e.Items) {
671        foreach (var parameter in analyzer.Value.Parameters.OfType<IScopeTreeLookupParameter>()) {
672          parameter.Depth = 3;
673        }
674      }
675    }
676
677    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
678      ParameterizeMainLoop();
679      ParameterizeSelectors();
680      ParameterizeAnalyzers();
681    }
682
683    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
684      ParameterizeSelectors();
685    }
686    private void Elites_ValueChanged(object sender, EventArgs e) {
687      ParameterizeSelectors();
688    }
689    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
690      ParameterizeSelectors();
691    }
692    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
693      ParameterizeSelectors();
694    }
695    private void NumberOfLayersParameter_ValueChanged(object sender, EventArgs e) {
696      NumberOfLayers.ValueChanged += NumberOfLayers_ValueChanged;
697      ParameterizeAgeLimits();
698    }
699    private void NumberOfLayers_ValueChanged(object sender, EventArgs e) {
700      ParameterizeAgeLimits();
701    }
702    private void AgeGapParameter_ValueChanged(object sender, EventArgs e) {
703      AgeGap.ValueChanged += AgeGap_ValueChanged;
704      ParameterizeAgeLimits();
705    }
706    private void AgeGap_ValueChanged(object sender, EventArgs e) {
707      ParameterizeAgeLimits();
708    }
709    private void AgingSchemeParameter_ValueChanged(object sender, EventArgs e) {
710      AgingScheme.ValueChanged += AgingScheme_ValueChanged;
711      ParameterizeAgeLimits();
712    }
713    private void AgingScheme_ValueChanged(object sender, EventArgs e) {
714      ParameterizeAgeLimits();
715    }
716
717    private void ParameterizeAgeLimits() {
718      var scheme = AgingScheme.Value;
719      int ageGap = AgeGap.Value;
720      int numberOfLayers = NumberOfLayers.Value;
721      AgeLimits = scheme.CalculateAgeLimits(ageGap, numberOfLayers);
722    }
723
724    private void ParameterizeMainLoop() {
725      //TODO
726      MainLoop.AgeGapParameter.ActualName = AgeGapParameter.Name;
727      MainLoop.AgeInheritanceParameter.ActualName = AgeInheritanceParameter.Name;
728      MainLoop.AgeLimitsParameter.ActualName = AgeLimitsParameter.Name;
729      MainLoop.ReduceToPopulationSizeParameter.ActualName = ReduceToPopulationSizeParameter.Name;
730      MainLoop.AgeParameter.ActualName = "Age";
731      MainLoop.GlobalRandomParameter.ActualName = "GlobalRandom";
732      MainLoop.IslandRandomParameter.ActualName = "IslandRandom";
733      MainLoop.LayerRandomParameter.ActualName = "LayerRandom";
734
735      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
736      MainLoop.LayerEvaluatedSolutionsParameter.ActualName = "LayerEvaluatedSolutions";
737
738      MainLoop.PlusSelectionParameter.ActualName = PlusSelectionParameter.Name;
739      MainLoop.NumberOfIslandsParameter.ActualName = NumberOfIslandsParameter.Name;
740      MainLoop.NumberOfLayersParameter.ActualName = NumberOfLayersParameter.Name;
741      MainLoop.MigrationIntervalParameter.ActualName = MigrationIntervalParameter.Name;
742      MainLoop.MigratorParameter.ActualName = MigratorParameter.Name;
743      MainLoop.EmigrantsSelectorParameter.ActualName = EmigrantsSelectorParameter.Name;
744      MainLoop.ImmigrationReplacerParameter.ActualName = ImmigrationReplacerParameter.Name;
745
746
747
748      MainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
749      MainLoop.CurrentPopulationSizeParameter.ActualName = "CurrentPopulationSize";
750      MainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
751      MainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
752      MainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
753      MainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
754      MainLoop.ElitesParameter.ActualName = ElitesParameter.Name;
755      MainLoop.TerminatorParameter.ActualName = TerminatorParameter.Name;
756
757      MainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
758      MainLoop.LayerAnalyzerParameter.ActualName = LayerAnalyzerParameter.Name;
759      MainLoop.IslandAnalyzerParameter.ActualName = IslandAnalyzerParameter.Name;
760      MainLoop.GroupAnalyzerParameter.ActualName = GroupAnalyzerParameter.Name;
761
762
763      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
764      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
765    }
766
767    private void ParametrizeMigration() {
768      var migrationSize = (int) Math.Ceiling(MigrationRateParameter.Value.Value *PopulationSize.Value);
769      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is IMultiObjectiveSelector)).OrderBy(x => x.Name)) {
770        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(migrationSize);
771        selector.NumberOfSelectedSubScopesParameter.Hidden = true;
772
773        ParameterizeStochasticOperatorForLayer(selector);
774
775        EmigrantsSelectorParameter.ValidValues.Add(selector);
776      }
777
778      foreach (IReplacer replacer in ApplicationManager.Manager.GetInstances<IReplacer>().OrderBy(x => x.Name)) {
779        ParameterizeStochasticOperatorForLayer(replacer);
780        ImmigrationReplacerParameter.ValidValues.Add(replacer);
781      }
782
783      MigratorParameter.ValidValues.Add(new LayerMigrator());
784    }
785
786    private void ParameterizeSolutionsCreator() {
787      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
788      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
789    }
790
791    private void ParameterizeSelectors() {
792      foreach (var selector in SelectorParameter.ValidValues) {
793        selector.CopySelected = new BoolValue(true);
794        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2*(PopulationSize.Value - Elites.Value));
795        selector.NumberOfSelectedSubScopesParameter.Hidden = true;
796        ParameterizeStochasticOperatorForLayer(selector);
797      }
798
799      if (Problem != null) {
800        foreach (var selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
801          ParametrizeSingleObjectiveSelector(selector);
802        }
803        foreach (var replacer in EmigrantsSelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
804          ParametrizeSingleObjectiveSelector(replacer);
805        }
806        foreach (var selector in ImmigrationReplacerParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
807          ParametrizeSingleObjectiveSelector(selector);
808        }
809
810      }
811    }
812
813    private void ParametrizeSingleObjectiveSelector(ISingleObjectiveSelector selector) {
814      selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
815      selector.MaximizationParameter.Hidden = true;
816      selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
817      selector.QualityParameter.Hidden = true;
818    }
819
820    private void ParameterizeAnalyzers() {
821      layerQualityAnalyzer.ResultsParameter.ActualName = "LayerResults";
822      layerQualityAnalyzer.ResultsParameter.Hidden = true;
823
824      islandQualityAnalyzer.ResultsParameter.ActualName = "IslandResults";
825      islandQualityAnalyzer.ResultsParameter.Hidden = true;
826
827      qualityAnalyzer.ResultsParameter.ActualName = "Results";
828      qualityAnalyzer.ResultsParameter.Hidden = true;
829
830      groupQualityAnalyzer.ResultsParameter.ActualName = "GroupResults";
831      groupQualityAnalyzer.ResultsParameter.Hidden = true;
832
833      if (Problem != null) {
834        SetAnalyzerParameter(layerQualityAnalyzer);
835        SetAnalyzerParameter(islandQualityAnalyzer);
836        SetAnalyzerParameter(qualityAnalyzer);
837        SetAnalyzerParameter(groupQualityAnalyzer);
838      }
839    }
840
841    private void SetAnalyzerParameter(BestAverageWorstQualityAnalyzer analyzer) {
842      analyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
843      analyzer.MaximizationParameter.Hidden = true;
844      analyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
845      analyzer.QualityParameter.Hidden = true;
846      analyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
847      analyzer.BestKnownQualityParameter.Hidden = true;
848    }
849
850    private void ParameterizeTerminators() {
851      qualityTerminator.Parameterize(qualityAnalyzer.CurrentBestQualityParameter, Problem);
852    }
853
854    private void ParameterizeIterationBasedOperators() {
855      if (Problem != null) {
856        foreach (var op in Problem.Operators.OfType<IIterationBasedOperator>()) {
857          op.IterationsParameter.ActualName = "Generations";
858          op.IterationsParameter.Hidden = true;
859          op.MaximumIterationsParameter.ActualName = generationsTerminator.ThresholdParameter.Name;
860          op.MaximumIterationsParameter.Hidden = true;
861        }
862      }
863    }
864
865    private void ParameterizeStochasticOperator(IOperator op) {
866      var stochasticOp = op as IStochasticOperator;
867      if (stochasticOp != null) {
868        stochasticOp.RandomParameter.ActualName = "GlobalRandom";
869        stochasticOp.RandomParameter.Hidden = true;
870      }
871    }
872
873    private void ParameterizeStochasticOperatorForLayer(IOperator op) {
874      var stochasticOp = op as IStochasticOperator;
875      if (stochasticOp != null) {
876        stochasticOp.RandomParameter.ActualName = "LayerRandom";
877        stochasticOp.RandomParameter.Hidden = true;
878      }
879    }
880
881    #endregion
882  }
883}
Note: See TracBrowser for help on using the repository browser.