source: branches/2839_HiveProjectManagement/HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm/3.3/IslandOffspringSelectionGeneticAlgorithm.cs @ 16057

Last change on this file since 16057 was 16057, checked in by jkarder, 15 months ago

#2839:

File size: 38.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Linq;
24using HeuristicLab.Analysis;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Optimization.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Random;
35
36namespace HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm {
37  /// <summary>
38  /// An offspring selection island genetic algorithm.
39  /// </summary>
40  [Item("Island Offspring Selection Genetic Algorithm (Island-OSGA)", "An island offspring selection genetic algorithm.")]
41  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 130)]
42  [StorableClass]
43  public sealed class IslandOffspringSelectionGeneticAlgorithm : HeuristicOptimizationEngineAlgorithm, IStorableContent {
44    public string Filename { get; set; }
45
46    #region Problem Properties
47    public override Type ProblemType {
48      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
49    }
50    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
51      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
52      set { base.Problem = value; }
53    }
54    #endregion
55
56    #region Parameter Properties
57    private ValueParameter<IntValue> SeedParameter {
58      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
59    }
60    private ValueParameter<BoolValue> SetSeedRandomlyParameter {
61      get { return (ValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
62    }
63    private ValueParameter<IntValue> NumberOfIslandsParameter {
64      get { return (ValueParameter<IntValue>)Parameters["NumberOfIslands"]; }
65    }
66    private ValueParameter<IntValue> MigrationIntervalParameter {
67      get { return (ValueParameter<IntValue>)Parameters["MigrationInterval"]; }
68    }
69    private ValueParameter<PercentValue> MigrationRateParameter {
70      get { return (ValueParameter<PercentValue>)Parameters["MigrationRate"]; }
71    }
72    public IConstrainedValueParameter<IMigrator> MigratorParameter {
73      get { return (IConstrainedValueParameter<IMigrator>)Parameters["Migrator"]; }
74    }
75    public IConstrainedValueParameter<ISelector> EmigrantsSelectorParameter {
76      get { return (IConstrainedValueParameter<ISelector>)Parameters["EmigrantsSelector"]; }
77    }
78    public IConstrainedValueParameter<IReplacer> ImmigrationReplacerParameter {
79      get { return (IConstrainedValueParameter<IReplacer>)Parameters["ImmigrationReplacer"]; }
80    }
81    private ValueParameter<IntValue> PopulationSizeParameter {
82      get { return (ValueParameter<IntValue>)Parameters["PopulationSize"]; }
83    }
84    private ValueParameter<IntValue> MaximumGenerationsParameter {
85      get { return (ValueParameter<IntValue>)Parameters["MaximumGenerations"]; }
86    }
87    public IConstrainedValueParameter<ISelector> SelectorParameter {
88      get { return (IConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
89    }
90    public IConstrainedValueParameter<ICrossover> CrossoverParameter {
91      get { return (IConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
92    }
93    private ValueParameter<PercentValue> MutationProbabilityParameter {
94      get { return (ValueParameter<PercentValue>)Parameters["MutationProbability"]; }
95    }
96    public IConstrainedValueParameter<IManipulator> MutatorParameter {
97      get { return (IConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
98    }
99    private ValueParameter<IntValue> ElitesParameter {
100      get { return (ValueParameter<IntValue>)Parameters["Elites"]; }
101    }
102    private IFixedValueParameter<BoolValue> ReevaluateElitesParameter {
103      get { return (IFixedValueParameter<BoolValue>)Parameters["ReevaluateElites"]; }
104    }
105    private ValueLookupParameter<DoubleValue> SuccessRatioParameter {
106      get { return (ValueLookupParameter<DoubleValue>)Parameters["SuccessRatio"]; }
107    }
108    private ValueLookupParameter<DoubleValue> ComparisonFactorLowerBoundParameter {
109      get { return (ValueLookupParameter<DoubleValue>)Parameters["ComparisonFactorLowerBound"]; }
110    }
111    private ValueLookupParameter<DoubleValue> ComparisonFactorUpperBoundParameter {
112      get { return (ValueLookupParameter<DoubleValue>)Parameters["ComparisonFactorUpperBound"]; }
113    }
114    public IConstrainedValueParameter<IDiscreteDoubleValueModifier> ComparisonFactorModifierParameter {
115      get { return (IConstrainedValueParameter<IDiscreteDoubleValueModifier>)Parameters["ComparisonFactorModifier"]; }
116    }
117    private ValueLookupParameter<DoubleValue> MaximumSelectionPressureParameter {
118      get { return (ValueLookupParameter<DoubleValue>)Parameters["MaximumSelectionPressure"]; }
119    }
120    private ValueLookupParameter<BoolValue> OffspringSelectionBeforeMutationParameter {
121      get { return (ValueLookupParameter<BoolValue>)Parameters["OffspringSelectionBeforeMutation"]; }
122    }
123    private ValueLookupParameter<IntValue> SelectedParentsParameter {
124      get { return (ValueLookupParameter<IntValue>)Parameters["SelectedParents"]; }
125    }
126    private ValueParameter<MultiAnalyzer> AnalyzerParameter {
127      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
128    }
129    private ValueParameter<MultiAnalyzer> IslandAnalyzerParameter {
130      get { return (ValueParameter<MultiAnalyzer>)Parameters["IslandAnalyzer"]; }
131    }
132    private ValueParameter<IntValue> MaximumEvaluatedSolutionsParameter {
133      get { return (ValueParameter<IntValue>)Parameters["MaximumEvaluatedSolutions"]; }
134    }
135    private IFixedValueParameter<BoolValue> FillPopulationWithParentsParameter {
136      get { return (IFixedValueParameter<BoolValue>)Parameters["FillPopulationWithParents"]; }
137    }
138    #endregion
139
140    #region Properties
141    public IntValue Seed {
142      get { return SeedParameter.Value; }
143      set { SeedParameter.Value = value; }
144    }
145    public BoolValue SetSeedRandomly {
146      get { return SetSeedRandomlyParameter.Value; }
147      set { SetSeedRandomlyParameter.Value = value; }
148    }
149    public IntValue NumberOfIslands {
150      get { return NumberOfIslandsParameter.Value; }
151      set { NumberOfIslandsParameter.Value = value; }
152    }
153    public IntValue MigrationInterval {
154      get { return MigrationIntervalParameter.Value; }
155      set { MigrationIntervalParameter.Value = value; }
156    }
157    public PercentValue MigrationRate {
158      get { return MigrationRateParameter.Value; }
159      set { MigrationRateParameter.Value = value; }
160    }
161    public IMigrator Migrator {
162      get { return MigratorParameter.Value; }
163      set { MigratorParameter.Value = value; }
164    }
165    public ISelector EmigrantsSelector {
166      get { return EmigrantsSelectorParameter.Value; }
167      set { EmigrantsSelectorParameter.Value = value; }
168    }
169    public IReplacer ImmigrationReplacer {
170      get { return ImmigrationReplacerParameter.Value; }
171      set { ImmigrationReplacerParameter.Value = value; }
172    }
173    public IntValue PopulationSize {
174      get { return PopulationSizeParameter.Value; }
175      set { PopulationSizeParameter.Value = value; }
176    }
177    public IntValue MaximumGenerations {
178      get { return MaximumGenerationsParameter.Value; }
179      set { MaximumGenerationsParameter.Value = value; }
180    }
181    public ISelector Selector {
182      get { return SelectorParameter.Value; }
183      set { SelectorParameter.Value = value; }
184    }
185    public ICrossover Crossover {
186      get { return CrossoverParameter.Value; }
187      set { CrossoverParameter.Value = value; }
188    }
189    public PercentValue MutationProbability {
190      get { return MutationProbabilityParameter.Value; }
191      set { MutationProbabilityParameter.Value = value; }
192    }
193    public IManipulator Mutator {
194      get { return MutatorParameter.Value; }
195      set { MutatorParameter.Value = value; }
196    }
197    public IntValue Elites {
198      get { return ElitesParameter.Value; }
199      set { ElitesParameter.Value = value; }
200    }
201    public bool ReevaluteElites {
202      get { return ReevaluateElitesParameter.Value.Value; }
203      set { ReevaluateElitesParameter.Value.Value = value; }
204    }
205    public DoubleValue SuccessRatio {
206      get { return SuccessRatioParameter.Value; }
207      set { SuccessRatioParameter.Value = value; }
208    }
209    public DoubleValue ComparisonFactorLowerBound {
210      get { return ComparisonFactorLowerBoundParameter.Value; }
211      set { ComparisonFactorLowerBoundParameter.Value = value; }
212    }
213    public DoubleValue ComparisonFactorUpperBound {
214      get { return ComparisonFactorUpperBoundParameter.Value; }
215      set { ComparisonFactorUpperBoundParameter.Value = value; }
216    }
217    public IDiscreteDoubleValueModifier ComparisonFactorModifier {
218      get { return ComparisonFactorModifierParameter.Value; }
219      set { ComparisonFactorModifierParameter.Value = value; }
220    }
221    public DoubleValue MaximumSelectionPressure {
222      get { return MaximumSelectionPressureParameter.Value; }
223      set { MaximumSelectionPressureParameter.Value = value; }
224    }
225    public BoolValue OffspringSelectionBeforeMutation {
226      get { return OffspringSelectionBeforeMutationParameter.Value; }
227      set { OffspringSelectionBeforeMutationParameter.Value = value; }
228    }
229    public MultiAnalyzer Analyzer {
230      get { return AnalyzerParameter.Value; }
231      set { AnalyzerParameter.Value = value; }
232    }
233    public MultiAnalyzer IslandAnalyzer {
234      get { return IslandAnalyzerParameter.Value; }
235      set { IslandAnalyzerParameter.Value = value; }
236    }
237    public IntValue MaximumEvaluatedSolutions {
238      get { return MaximumEvaluatedSolutionsParameter.Value; }
239      set { MaximumEvaluatedSolutionsParameter.Value = value; }
240    }
241    public bool FillPopulationWithParents {
242      get { return FillPopulationWithParentsParameter.Value.Value; }
243      set { FillPopulationWithParentsParameter.Value.Value = value; }
244    }
245    private RandomCreator RandomCreator {
246      get { return (RandomCreator)OperatorGraph.InitialOperator; }
247    }
248    private UniformSubScopesProcessor IslandProcessor {
249      get { return ((RandomCreator.Successor as SubScopesCreator).Successor as UniformSubScopesProcessor); }
250    }
251    private SolutionsCreator SolutionsCreator {
252      get { return (SolutionsCreator)IslandProcessor.Operator; }
253    }
254    private IslandOffspringSelectionGeneticAlgorithmMainLoop MainLoop {
255      get { return FindMainLoop(IslandProcessor.Successor); }
256    }
257    [Storable]
258    private BestAverageWorstQualityAnalyzer islandQualityAnalyzer;
259    [Storable]
260    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
261    [Storable]
262    private ValueAnalyzer islandSelectionPressureAnalyzer;
263    [Storable]
264    private ValueAnalyzer selectionPressureAnalyzer;
265    [Storable]
266    private SuccessfulOffspringAnalyzer successfulOffspringAnalyzer;
267    #endregion
268
269    [StorableConstructor]
270    private IslandOffspringSelectionGeneticAlgorithm(bool deserializing) : base(deserializing) { }
271    [StorableHook(HookType.AfterDeserialization)]
272    private void AfterDeserialization() {
273      // BackwardsCompatibility3.3
274      #region Backwards compatible code, remove with 3.4
275      if (successfulOffspringAnalyzer == null)
276        successfulOffspringAnalyzer = new SuccessfulOffspringAnalyzer();
277      if (!Parameters.ContainsKey("ReevaluateElites")) {
278        Parameters.Add(new FixedValueParameter<BoolValue>("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)", (BoolValue)new BoolValue(false).AsReadOnly()) { Hidden = true });
279      }
280      if (!Parameters.ContainsKey("FillPopulationWithParents"))
281        Parameters.Add(new FixedValueParameter<BoolValue>("FillPopulationWithParents", "True if the population should be filled with parent individual or false if worse children should be used when the maximum selection pressure is exceeded.", new BoolValue(false)) { Hidden = true });
282
283      var optionalMutatorParameter = MutatorParameter as OptionalConstrainedValueParameter<IManipulator>;
284      if (optionalMutatorParameter != null) {
285        Parameters.Remove(optionalMutatorParameter);
286        Parameters.Add(new ConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
287        foreach (var m in optionalMutatorParameter.ValidValues)
288          MutatorParameter.ValidValues.Add(m);
289        if (optionalMutatorParameter.Value == null) MutationProbability.Value = 0; // to guarantee that the old configuration results in the same behavior
290        else Mutator = optionalMutatorParameter.Value;
291        optionalMutatorParameter.ValidValues.Clear(); // to avoid dangling references to the old parameter its valid values are cleared
292      }
293      #endregion
294
295      Initialize();
296    }
297    private IslandOffspringSelectionGeneticAlgorithm(IslandOffspringSelectionGeneticAlgorithm original, Cloner cloner)
298      : base(original, cloner) {
299      islandQualityAnalyzer = cloner.Clone(original.islandQualityAnalyzer);
300      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
301      islandSelectionPressureAnalyzer = cloner.Clone(original.islandSelectionPressureAnalyzer);
302      selectionPressureAnalyzer = cloner.Clone(original.selectionPressureAnalyzer);
303      successfulOffspringAnalyzer = cloner.Clone(original.successfulOffspringAnalyzer);
304      Initialize();
305    }
306    public override IDeepCloneable Clone(Cloner cloner) {
307      return new IslandOffspringSelectionGeneticAlgorithm(this, cloner);
308    }
309    public IslandOffspringSelectionGeneticAlgorithm()
310      : base() {
311      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
312      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
313      Parameters.Add(new ValueParameter<IntValue>("NumberOfIslands", "The number of islands.", new IntValue(5)));
314      Parameters.Add(new ValueParameter<IntValue>("MigrationInterval", "The number of generations that should pass between migration phases.", new IntValue(20)));
315      Parameters.Add(new ValueParameter<PercentValue>("MigrationRate", "The proportion of individuals that should migrate between the islands.", new PercentValue(0.15)));
316      Parameters.Add(new ConstrainedValueParameter<IMigrator>("Migrator", "The migration strategy."));
317      Parameters.Add(new ConstrainedValueParameter<ISelector>("EmigrantsSelector", "Selects the individuals that will be migrated."));
318      Parameters.Add(new ConstrainedValueParameter<IReplacer>("ImmigrationReplacer", "Replaces part of the original population with the immigrants."));
319      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions of each island.", new IntValue(100)));
320      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations that should be processed.", new IntValue(100)));
321      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
322      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
323      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
324      Parameters.Add(new ConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
325      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
326      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 });
327      Parameters.Add(new ValueLookupParameter<DoubleValue>("SuccessRatio", "The ratio of successful to total children that should be achieved.", new DoubleValue(1)));
328      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactorLowerBound", "The lower bound of the comparison factor (start).", new DoubleValue(0)));
329      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactorUpperBound", "The upper bound of the comparison factor (end).", new DoubleValue(1)));
330      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("ComparisonFactorModifier", "The operator used to modify the comparison factor.", new ItemSet<IDiscreteDoubleValueModifier>(new IDiscreteDoubleValueModifier[] { new LinearDiscreteDoubleValueModifier() }), new LinearDiscreteDoubleValueModifier()));
331      Parameters.Add(new ValueLookupParameter<DoubleValue>("MaximumSelectionPressure", "The maximum selection pressure that terminates the algorithm.", new DoubleValue(100)));
332      Parameters.Add(new ValueLookupParameter<BoolValue>("OffspringSelectionBeforeMutation", "True if the offspring selection step should be applied before mutation, false if it should be applied after mutation.", new BoolValue(false)));
333      Parameters.Add(new ValueLookupParameter<IntValue>("SelectedParents", "How much parents should be selected each time the offspring selection step is performed until the population is filled. This parameter should be about the same or twice the size of PopulationSize for smaller problems, and less for large problems.", new IntValue(200)));
334      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the islands.", new MultiAnalyzer()));
335      Parameters.Add(new ValueParameter<MultiAnalyzer>("IslandAnalyzer", "The operator used to analyze each island.", new MultiAnalyzer()));
336      Parameters.Add(new ValueParameter<IntValue>("MaximumEvaluatedSolutions", "The maximum number of evaluated solutions (approximately).", new IntValue(int.MaxValue)));
337      Parameters.Add(new FixedValueParameter<BoolValue>("FillPopulationWithParents", "True if the population should be filled with parent individual or false if worse children should be used when the maximum selection pressure is exceeded.", new BoolValue(true)) { Hidden = true });
338
339      RandomCreator randomCreator = new RandomCreator();
340      SubScopesCreator populationCreator = new SubScopesCreator();
341      UniformSubScopesProcessor ussp1 = new UniformSubScopesProcessor();
342      SolutionsCreator solutionsCreator = new SolutionsCreator();
343      VariableCreator variableCreator = new VariableCreator();
344      UniformSubScopesProcessor ussp2 = new UniformSubScopesProcessor();
345      SubScopesCounter subScopesCounter = new SubScopesCounter();
346      ResultsCollector resultsCollector = new ResultsCollector();
347      IslandOffspringSelectionGeneticAlgorithmMainLoop mainLoop = new IslandOffspringSelectionGeneticAlgorithmMainLoop();
348      OperatorGraph.InitialOperator = randomCreator;
349
350      randomCreator.RandomParameter.ActualName = "Random";
351      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
352      randomCreator.SeedParameter.Value = null;
353      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
354      randomCreator.SetSeedRandomlyParameter.Value = null;
355      randomCreator.Successor = populationCreator;
356
357      populationCreator.NumberOfSubScopesParameter.ActualName = NumberOfIslandsParameter.Name;
358      populationCreator.Successor = ussp1;
359
360      ussp1.Operator = solutionsCreator;
361      ussp1.Successor = variableCreator;
362
363      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
364      solutionsCreator.Successor = null;
365
366      variableCreator.Name = "Initialize EvaluatedSolutions";
367      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue()));
368      variableCreator.Successor = ussp2;
369
370      ussp2.Operator = subScopesCounter;
371      ussp2.Successor = resultsCollector;
372
373      subScopesCounter.Name = "Increment EvaluatedSolutions";
374      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
375
376      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", "", "EvaluatedSolutions"));
377      resultsCollector.ResultsParameter.ActualName = "Results";
378      resultsCollector.Successor = mainLoop;
379
380      mainLoop.EmigrantsSelectorParameter.ActualName = EmigrantsSelectorParameter.Name;
381      mainLoop.ImmigrationReplacerParameter.ActualName = ImmigrationReplacerParameter.Name;
382      mainLoop.MaximumGenerationsParameter.ActualName = MaximumGenerationsParameter.Name;
383      mainLoop.MigrationIntervalParameter.ActualName = MigrationIntervalParameter.Name;
384      mainLoop.MigrationRateParameter.ActualName = MigrationRateParameter.Name;
385      mainLoop.MigratorParameter.ActualName = MigratorParameter.Name;
386      mainLoop.NumberOfIslandsParameter.ActualName = NumberOfIslandsParameter.Name;
387      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
388      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
389      mainLoop.ElitesParameter.ActualName = ElitesParameter.Name;
390      mainLoop.ReevaluateElitesParameter.ActualName = ReevaluateElitesParameter.Name;
391      mainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
392      mainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
393      mainLoop.RandomParameter.ActualName = randomCreator.RandomParameter.ActualName;
394      mainLoop.ResultsParameter.ActualName = "Results";
395      mainLoop.SuccessRatioParameter.ActualName = SuccessRatioParameter.Name;
396      mainLoop.ComparisonFactorParameter.ActualName = "ComparisonFactor";
397      mainLoop.ComparisonFactorStartParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
398      mainLoop.ComparisonFactorModifierParameter.ActualName = ComparisonFactorModifierParameter.Name;
399      mainLoop.MaximumSelectionPressureParameter.ActualName = MaximumSelectionPressureParameter.Name;
400      mainLoop.OffspringSelectionBeforeMutationParameter.ActualName = OffspringSelectionBeforeMutationParameter.Name;
401      mainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
402      mainLoop.FillPopulationWithParentsParameter.ActualName = FillPopulationWithParentsParameter.Name;
403      mainLoop.Successor = null;
404
405      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is IMultiObjectiveSelector)).OrderBy(x => x.Name))
406        SelectorParameter.ValidValues.Add(selector);
407      ISelector proportionalSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("ProportionalSelector"));
408      if (proportionalSelector != null) SelectorParameter.Value = proportionalSelector;
409
410      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is IMultiObjectiveSelector)).OrderBy(x => x.Name))
411        EmigrantsSelectorParameter.ValidValues.Add(selector);
412
413      foreach (IReplacer replacer in ApplicationManager.Manager.GetInstances<IReplacer>().OrderBy(x => x.Name))
414        ImmigrationReplacerParameter.ValidValues.Add(replacer);
415
416      ParameterizeSelectors();
417
418      foreach (IMigrator migrator in ApplicationManager.Manager.GetInstances<IMigrator>().OrderBy(x => x.Name)) {
419        // BackwardsCompatibility3.3
420        // Set the migration direction to counterclockwise
421        var unidirectionalRing = migrator as UnidirectionalRingMigrator;
422        if (unidirectionalRing != null) unidirectionalRing.ClockwiseMigrationParameter.Value = new BoolValue(false);
423        MigratorParameter.ValidValues.Add(migrator);
424      }
425
426      foreach (IDiscreteDoubleValueModifier modifier in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name))
427        ComparisonFactorModifierParameter.ValidValues.Add(modifier);
428      IDiscreteDoubleValueModifier linearModifier = ComparisonFactorModifierParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("LinearDiscreteDoubleValueModifier"));
429      if (linearModifier != null) ComparisonFactorModifierParameter.Value = linearModifier;
430      ParameterizeComparisonFactorModifiers();
431
432      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
433      islandQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
434      selectionPressureAnalyzer = new ValueAnalyzer();
435      islandSelectionPressureAnalyzer = new ValueAnalyzer();
436      successfulOffspringAnalyzer = new SuccessfulOffspringAnalyzer();
437      ParameterizeAnalyzers();
438      UpdateAnalyzers();
439
440      Initialize();
441    }
442    public override void Prepare() {
443      if (Problem != null) base.Prepare();
444    }
445
446    #region Events
447    protected override void OnProblemChanged() {
448      ParameterizeStochasticOperator(Problem.SolutionCreator);
449      ParameterizeStochasticOperator(Problem.Evaluator);
450      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
451      ParameterizeSolutionsCreator();
452      ParameterizeMainLoop();
453      ParameterizeSelectors();
454      ParameterizeAnalyzers();
455      ParameterizeIterationBasedOperators();
456      UpdateCrossovers();
457      UpdateMutators();
458      UpdateAnalyzers();
459      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
460      base.OnProblemChanged();
461    }
462
463    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
464      ParameterizeStochasticOperator(Problem.SolutionCreator);
465      ParameterizeSolutionsCreator();
466      base.Problem_SolutionCreatorChanged(sender, e);
467    }
468    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
469      ParameterizeStochasticOperator(Problem.Evaluator);
470      ParameterizeSolutionsCreator();
471      ParameterizeMainLoop();
472      ParameterizeSelectors();
473      ParameterizeAnalyzers();
474      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
475      base.Problem_EvaluatorChanged(sender, e);
476    }
477    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
478      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
479      ParameterizeIterationBasedOperators();
480      UpdateCrossovers();
481      UpdateMutators();
482      UpdateAnalyzers();
483      base.Problem_OperatorsChanged(sender, e);
484    }
485    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
486      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
487      ParameterizeSelectors();
488    }
489    private void Elites_ValueChanged(object sender, EventArgs e) {
490      ParameterizeSelectors();
491    }
492    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
493      NumberOfIslands.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
494      ParameterizeSelectors();
495    }
496    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
497      ParameterizeSelectors();
498    }
499    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
500      ParameterizeMainLoop();
501      ParameterizeSelectors();
502      ParameterizeAnalyzers();
503    }
504    private void MigrationRateParameter_ValueChanged(object sender, EventArgs e) {
505      MigrationRate.ValueChanged += new EventHandler(MigrationRate_ValueChanged);
506      ParameterizeSelectors();
507    }
508    private void MigrationRate_ValueChanged(object sender, EventArgs e) {
509      ParameterizeSelectors();
510    }
511    private void MaximumMigrationsParameter_ValueChanged(object sender, EventArgs e) {
512      MaximumGenerations.ValueChanged += new EventHandler(MaximumMigrations_ValueChanged);
513      ParameterizeComparisonFactorModifiers();
514    }
515    private void MaximumMigrations_ValueChanged(object sender, EventArgs e) {
516      ParameterizeComparisonFactorModifiers();
517    }
518    private void MigrationIntervalParameter_ValueChanged(object sender, EventArgs e) {
519      MigrationInterval.ValueChanged += new EventHandler(MigrationInterval_ValueChanged);
520      ParameterizeComparisonFactorModifiers();
521    }
522    private void MigrationInterval_ValueChanged(object sender, EventArgs e) {
523      ParameterizeComparisonFactorModifiers();
524    }
525    #endregion
526
527    #region Helpers
528    private void Initialize() {
529      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
530      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
531      MigrationRateParameter.ValueChanged += new EventHandler(MigrationRateParameter_ValueChanged);
532      MigrationRate.ValueChanged += new EventHandler(MigrationRate_ValueChanged);
533      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
534      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
535      MigrationIntervalParameter.ValueChanged += new EventHandler(MigrationIntervalParameter_ValueChanged);
536      MigrationInterval.ValueChanged += new EventHandler(MigrationInterval_ValueChanged);
537      MaximumGenerationsParameter.ValueChanged += new EventHandler(MaximumMigrationsParameter_ValueChanged);
538      MaximumGenerations.ValueChanged += new EventHandler(MaximumMigrations_ValueChanged);
539      if (Problem != null) {
540        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
541      }
542    }
543    private void ParameterizeSolutionsCreator() {
544      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
545      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
546    }
547    private void ParameterizeMainLoop() {
548      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
549      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
550      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
551      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
552    }
553    private void ParameterizeStochasticOperator(IOperator op) {
554      if (op is IStochasticOperator)
555        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
556    }
557    private void ParameterizeSelectors() {
558      foreach (ISelector selector in SelectorParameter.ValidValues) {
559        selector.CopySelected = new BoolValue(true);
560        selector.NumberOfSelectedSubScopesParameter.Value = null;
561        selector.NumberOfSelectedSubScopesParameter.ActualName = SelectedParentsParameter.Name;
562        ParameterizeStochasticOperator(selector);
563      }
564      foreach (ISelector selector in EmigrantsSelectorParameter.ValidValues) {
565        selector.CopySelected = new BoolValue(true);
566        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue((int)Math.Ceiling(PopulationSize.Value * MigrationRate.Value));
567        ParameterizeStochasticOperator(selector);
568      }
569      foreach (IReplacer selector in ImmigrationReplacerParameter.ValidValues) {
570        ParameterizeStochasticOperator(selector);
571      }
572      if (Problem != null) {
573        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
574          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
575          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
576        }
577        foreach (ISingleObjectiveSelector selector in EmigrantsSelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
578          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
579          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
580        }
581        foreach (ISingleObjectiveReplacer replacer in ImmigrationReplacerParameter.ValidValues.OfType<ISingleObjectiveReplacer>()) {
582          replacer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
583          replacer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
584        }
585      }
586    }
587    private void ParameterizeAnalyzers() {
588      islandQualityAnalyzer.ResultsParameter.ActualName = "Results";
589      islandQualityAnalyzer.QualityParameter.Depth = 1;
590      qualityAnalyzer.ResultsParameter.ActualName = "Results";
591      qualityAnalyzer.QualityParameter.Depth = 2;
592
593      islandSelectionPressureAnalyzer.ResultsParameter.ActualName = "Results";
594      islandSelectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
595      islandSelectionPressureAnalyzer.ValueParameter.Depth = 0;
596      islandSelectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
597      islandSelectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
598
599      selectionPressureAnalyzer.ResultsParameter.ActualName = "Results";
600      selectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
601      selectionPressureAnalyzer.ValueParameter.Depth = 1;
602      selectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
603      selectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
604
605      successfulOffspringAnalyzer.ResultsParameter.ActualName = "Results";
606      successfulOffspringAnalyzer.GenerationsParameter.ActualName = "Generations";
607      successfulOffspringAnalyzer.SuccessfulOffspringFlagParameter.Value.Value = "SuccessfulOffspring";
608      successfulOffspringAnalyzer.DepthParameter.Value = new IntValue(2);
609
610      if (Problem != null) {
611        islandQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
612        islandQualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
613        islandQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
614
615        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
616        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
617        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
618      }
619    }
620    private void ParameterizeComparisonFactorModifiers() {
621      foreach (IDiscreteDoubleValueModifier modifier in ComparisonFactorModifierParameter.ValidValues) {
622        modifier.IndexParameter.ActualName = "Generations";
623        modifier.EndIndexParameter.Value = new IntValue(MigrationInterval.Value * MaximumGenerations.Value);
624        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
625        modifier.StartIndexParameter.Value = new IntValue(0);
626        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
627        modifier.ValueParameter.ActualName = "ComparisonFactor";
628      }
629    }
630    private void ParameterizeIterationBasedOperators() {
631      if (Problem != null) {
632        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
633          op.IterationsParameter.ActualName = "Generations";
634          op.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name;
635        }
636      }
637    }
638    private void UpdateCrossovers() {
639      ICrossover oldCrossover = CrossoverParameter.Value;
640      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
641      CrossoverParameter.ValidValues.Clear();
642      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
643        CrossoverParameter.ValidValues.Add(crossover);
644      if (oldCrossover != null) {
645        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
646        if (crossover != null) CrossoverParameter.Value = crossover;
647        else oldCrossover = null;
648      }
649      if (oldCrossover == null && defaultCrossover != null)
650        CrossoverParameter.Value = defaultCrossover;
651    }
652    private void UpdateMutators() {
653      IManipulator oldMutator = MutatorParameter.Value;
654      MutatorParameter.ValidValues.Clear();
655      IManipulator defaultMutator = Problem.Operators.OfType<IManipulator>().FirstOrDefault();
656
657      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
658        MutatorParameter.ValidValues.Add(mutator);
659
660      if (oldMutator != null) {
661        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
662        if (mutator != null) MutatorParameter.Value = mutator;
663        else oldMutator = null;
664      }
665
666      if (oldMutator == null && defaultMutator != null)
667        MutatorParameter.Value = defaultMutator;
668    }
669    private void UpdateAnalyzers() {
670      IslandAnalyzer.Operators.Clear();
671      Analyzer.Operators.Clear();
672      IslandAnalyzer.Operators.Add(islandQualityAnalyzer, islandQualityAnalyzer.EnabledByDefault);
673      IslandAnalyzer.Operators.Add(islandSelectionPressureAnalyzer, islandSelectionPressureAnalyzer.EnabledByDefault);
674      if (Problem != null) {
675        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
676          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
677            param.Depth = 2;
678          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
679        }
680      }
681      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
682      Analyzer.Operators.Add(selectionPressureAnalyzer, selectionPressureAnalyzer.EnabledByDefault);
683      Analyzer.Operators.Add(successfulOffspringAnalyzer, successfulOffspringAnalyzer.EnabledByDefault);
684    }
685    private IslandOffspringSelectionGeneticAlgorithmMainLoop FindMainLoop(IOperator start) {
686      IOperator mainLoop = start;
687      while (mainLoop != null && !(mainLoop is IslandOffspringSelectionGeneticAlgorithmMainLoop))
688        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
689      if (mainLoop == null) return null;
690      else return (IslandOffspringSelectionGeneticAlgorithmMainLoop)mainLoop;
691    }
692    #endregion
693  }
694}
Note: See TracBrowser for help on using the repository browser.