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

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

#2558 Added GroupedLayerAnalyzer
Fixed an evaluated solutions bug

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