Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2258_IslandALPS/IslandALPS/3.3/IslandALPSAlgorithm.cs @ 16674

Last change on this file since 16674 was 13962, checked in by pkuelzer, 8 years ago

#2558 cloning constructor to public

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