Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysis.IslandAlgorithms/HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm/3.3/IslandOffspringSelectionGeneticAlgorithm.cs @ 10591

Last change on this file since 10591 was 10389, checked in by mkommend, 10 years ago

#1997: Corrected API of island offspring selection algorithm (some properties were not accessible).

File size: 37.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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", "An island offspring selection genetic algorithm.")]
41  [Creatable("Algorithms")]
42  [StorableClass]
43  public 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    protected ValueParameter<IntValue> SeedParameter {
58      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
59    }
60    protected ValueParameter<BoolValue> SetSeedRandomlyParameter {
61      get { return (ValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
62    }
63    protected ValueParameter<IntValue> NumberOfIslandsParameter {
64      get { return (ValueParameter<IntValue>)Parameters["NumberOfIslands"]; }
65    }
66    protected ValueParameter<IntValue> MigrationIntervalParameter {
67      get { return (ValueParameter<IntValue>)Parameters["MigrationInterval"]; }
68    }
69    protected 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    protected ValueParameter<IntValue> PopulationSizeParameter {
82      get { return (ValueParameter<IntValue>)Parameters["PopulationSize"]; }
83    }
84    protected 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    protected 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    protected ValueParameter<IntValue> ElitesParameter {
100      get { return (ValueParameter<IntValue>)Parameters["Elites"]; }
101    }
102    protected IFixedValueParameter<BoolValue> ReevaluateElitesParameter {
103      get { return (IFixedValueParameter<BoolValue>)Parameters["ReevaluateElites"]; }
104    }
105    protected ValueLookupParameter<DoubleValue> SuccessRatioParameter {
106      get { return (ValueLookupParameter<DoubleValue>)Parameters["SuccessRatio"]; }
107    }
108    protected ValueLookupParameter<DoubleValue> ComparisonFactorLowerBoundParameter {
109      get { return (ValueLookupParameter<DoubleValue>)Parameters["ComparisonFactorLowerBound"]; }
110    }
111    protected 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    protected ValueLookupParameter<DoubleValue> MaximumSelectionPressureParameter {
118      get { return (ValueLookupParameter<DoubleValue>)Parameters["MaximumSelectionPressure"]; }
119    }
120    protected ValueLookupParameter<BoolValue> OffspringSelectionBeforeMutationParameter {
121      get { return (ValueLookupParameter<BoolValue>)Parameters["OffspringSelectionBeforeMutation"]; }
122    }
123    protected ValueLookupParameter<IntValue> SelectedParentsParameter {
124      get { return (ValueLookupParameter<IntValue>)Parameters["SelectedParents"]; }
125    }
126    protected ValueParameter<MultiAnalyzer> AnalyzerParameter {
127      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
128    }
129    protected ValueParameter<MultiAnalyzer> IslandAnalyzerParameter {
130      get { return (ValueParameter<MultiAnalyzer>)Parameters["IslandAnalyzer"]; }
131    }
132    protected ValueParameter<IntValue> MaximumEvaluatedSolutionsParameter {
133      get { return (ValueParameter<IntValue>)Parameters["MaximumEvaluatedSolutions"]; }
134    }
135    protected IFixedValueParameter<BoolValue> ReevaluateImmigrantsParameter {
136      get { return (IFixedValueParameter<BoolValue>)Parameters["ReevaluateImmigrants"]; }
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      private set { SuccessRatioParameter.Value = value; }
208    }
209    public DoubleValue ComparisonFactorLowerBound {
210      get { return ComparisonFactorLowerBoundParameter.Value; }
211      private set { ComparisonFactorLowerBoundParameter.Value = value; }
212    }
213    public DoubleValue ComparisonFactorUpperBound {
214      get { return ComparisonFactorUpperBoundParameter.Value; }
215      private 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      private set { MaximumSelectionPressureParameter.Value = value; }
224    }
225    public BoolValue OffspringSelectionBeforeMutation {
226      get { return OffspringSelectionBeforeMutationParameter.Value; }
227      private 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 ReevaluateImmigrants {
242      get { return ReevaluateImmigrantsParameter.Value.Value; }
243      set { ReevaluateImmigrantsParameter.Value.Value = value; }
244    }
245    protected RandomCreator RandomCreator {
246      get { return (RandomCreator)OperatorGraph.InitialOperator; }
247    }
248    protected UniformSubScopesProcessor IslandProcessor {
249      get { return OperatorGraph.Iterate().OfType<UniformSubScopesProcessor>().First(x => x.Operator is SolutionsCreator); }
250    }
251    protected SolutionsCreator SolutionsCreator {
252      get { return (SolutionsCreator)IslandProcessor.Operator; }
253    }
254    protected 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    protected 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("ReevaluateImmigrants")) {
281        Parameters.Add(new FixedValueParameter<BoolValue>("ReevaluateImmigrants", "Flag which indicates if inviduals should be reevaluated before they are immigrated.", new BoolValue(false)) { Hidden = true });
282      }
283      #endregion
284
285      Initialize();
286    }
287    protected IslandOffspringSelectionGeneticAlgorithm(IslandOffspringSelectionGeneticAlgorithm original, Cloner cloner)
288      : base(original, cloner) {
289      islandQualityAnalyzer = cloner.Clone(original.islandQualityAnalyzer);
290      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
291      islandSelectionPressureAnalyzer = cloner.Clone(original.islandSelectionPressureAnalyzer);
292      selectionPressureAnalyzer = cloner.Clone(original.selectionPressureAnalyzer);
293      successfulOffspringAnalyzer = cloner.Clone(original.successfulOffspringAnalyzer);
294      Initialize();
295    }
296    public override IDeepCloneable Clone(Cloner cloner) {
297      return new IslandOffspringSelectionGeneticAlgorithm(this, cloner);
298    }
299    public IslandOffspringSelectionGeneticAlgorithm()
300      : base() {
301      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
302      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
303      Parameters.Add(new ValueParameter<IntValue>("NumberOfIslands", "The number of islands.", new IntValue(5)));
304      Parameters.Add(new ValueParameter<IntValue>("MigrationInterval", "The number of generations that should pass between migration phases.", new IntValue(20)));
305      Parameters.Add(new ValueParameter<PercentValue>("MigrationRate", "The proportion of individuals that should migrate between the islands.", new PercentValue(0.15)));
306      Parameters.Add(new ConstrainedValueParameter<IMigrator>("Migrator", "The migration strategy."));
307      Parameters.Add(new ConstrainedValueParameter<ISelector>("EmigrantsSelector", "Selects the individuals that will be migrated."));
308      Parameters.Add(new ConstrainedValueParameter<IReplacer>("ImmigrationReplacer", "Replaces part of the original population with the immigrants."));
309      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions of each island.", new IntValue(100)));
310      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations that should be processed.", new IntValue(100)));
311      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
312      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
313      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
314      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
315      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
316      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 });
317      Parameters.Add(new ValueLookupParameter<DoubleValue>("SuccessRatio", "The ratio of successful to total children that should be achieved.", new DoubleValue(1)));
318      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactorLowerBound", "The lower bound of the comparison factor (start).", new DoubleValue(0)));
319      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactorUpperBound", "The upper bound of the comparison factor (end).", new DoubleValue(1)));
320      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("ComparisonFactorModifier", "The operator used to modify the comparison factor.", new ItemSet<IDiscreteDoubleValueModifier>(new IDiscreteDoubleValueModifier[] { new LinearDiscreteDoubleValueModifier() }), new LinearDiscreteDoubleValueModifier()));
321      Parameters.Add(new ValueLookupParameter<DoubleValue>("MaximumSelectionPressure", "The maximum selection pressure that terminates the algorithm.", new DoubleValue(100)));
322      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)));
323      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)));
324      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the islands.", new MultiAnalyzer()));
325      Parameters.Add(new ValueParameter<MultiAnalyzer>("IslandAnalyzer", "The operator used to analyze each island.", new MultiAnalyzer()));
326      Parameters.Add(new ValueParameter<IntValue>("MaximumEvaluatedSolutions", "The maximum number of evaluated solutions (approximately).", new IntValue(int.MaxValue)));
327      Parameters.Add(new FixedValueParameter<BoolValue>("ReevaluateImmigrants", "Flag which indicates if inviduals should be reevaluated before they are immigrated.", new BoolValue(false)) { Hidden = true });
328
329      RandomCreator randomCreator = new RandomCreator();
330      SubScopesCreator populationCreator = new SubScopesCreator();
331      UniformSubScopesProcessor ussp1 = new UniformSubScopesProcessor();
332      SolutionsCreator solutionsCreator = new SolutionsCreator();
333      VariableCreator variableCreator = new VariableCreator();
334      UniformSubScopesProcessor ussp2 = new UniformSubScopesProcessor();
335      SubScopesCounter subScopesCounter = new SubScopesCounter();
336      ResultsCollector resultsCollector = new ResultsCollector();
337      IslandOffspringSelectionGeneticAlgorithmMainLoop mainLoop = new IslandOffspringSelectionGeneticAlgorithmMainLoop();
338      OperatorGraph.InitialOperator = randomCreator;
339
340      randomCreator.RandomParameter.ActualName = "Random";
341      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
342      randomCreator.SeedParameter.Value = null;
343      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
344      randomCreator.SetSeedRandomlyParameter.Value = null;
345      randomCreator.Successor = populationCreator;
346
347      populationCreator.NumberOfSubScopesParameter.ActualName = NumberOfIslandsParameter.Name;
348      populationCreator.Successor = ussp1;
349
350      ussp1.Operator = solutionsCreator;
351      ussp1.Successor = variableCreator;
352
353      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
354      solutionsCreator.Successor = null;
355
356      variableCreator.Name = "Initialize EvaluatedSolutions";
357      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue()));
358      variableCreator.Successor = ussp2;
359
360      ussp2.Operator = subScopesCounter;
361      ussp2.Successor = resultsCollector;
362
363      subScopesCounter.Name = "Increment EvaluatedSolutions";
364      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
365
366      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", "", "EvaluatedSolutions"));
367      resultsCollector.ResultsParameter.ActualName = "Results";
368      resultsCollector.Successor = mainLoop;
369
370      mainLoop.EmigrantsSelectorParameter.ActualName = EmigrantsSelectorParameter.Name;
371      mainLoop.ImmigrationReplacerParameter.ActualName = ImmigrationReplacerParameter.Name;
372      mainLoop.MaximumGenerationsParameter.ActualName = MaximumGenerationsParameter.Name;
373      mainLoop.MigrationIntervalParameter.ActualName = MigrationIntervalParameter.Name;
374      mainLoop.MigrationRateParameter.ActualName = MigrationRateParameter.Name;
375      mainLoop.MigratorParameter.ActualName = MigratorParameter.Name;
376      mainLoop.NumberOfIslandsParameter.ActualName = NumberOfIslandsParameter.Name;
377      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
378      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
379      mainLoop.ElitesParameter.ActualName = ElitesParameter.Name;
380      mainLoop.ReevaluateElitesParameter.ActualName = ReevaluateElitesParameter.Name;
381      mainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
382      mainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
383      mainLoop.RandomParameter.ActualName = randomCreator.RandomParameter.ActualName;
384      mainLoop.ResultsParameter.ActualName = "Results";
385      mainLoop.SuccessRatioParameter.ActualName = SuccessRatioParameter.Name;
386      mainLoop.ComparisonFactorParameter.ActualName = "ComparisonFactor";
387      mainLoop.ComparisonFactorStartParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
388      mainLoop.ComparisonFactorModifierParameter.ActualName = ComparisonFactorModifierParameter.Name;
389      mainLoop.MaximumSelectionPressureParameter.ActualName = MaximumSelectionPressureParameter.Name;
390      mainLoop.OffspringSelectionBeforeMutationParameter.ActualName = OffspringSelectionBeforeMutationParameter.Name;
391      mainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
392      mainLoop.Successor = null;
393
394      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is IMultiObjectiveSelector)).OrderBy(x => x.Name))
395        SelectorParameter.ValidValues.Add(selector);
396      ISelector proportionalSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("ProportionalSelector"));
397      if (proportionalSelector != null) SelectorParameter.Value = proportionalSelector;
398
399      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is IMultiObjectiveSelector)).OrderBy(x => x.Name))
400        EmigrantsSelectorParameter.ValidValues.Add(selector);
401
402      foreach (IReplacer replacer in ApplicationManager.Manager.GetInstances<IReplacer>().OrderBy(x => x.Name))
403        ImmigrationReplacerParameter.ValidValues.Add(replacer);
404
405      ParameterizeSelectors();
406
407      foreach (IMigrator migrator in ApplicationManager.Manager.GetInstances<IMigrator>().OrderBy(x => x.Name))
408        MigratorParameter.ValidValues.Add(migrator);
409
410      foreach (IDiscreteDoubleValueModifier modifier in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name))
411        ComparisonFactorModifierParameter.ValidValues.Add(modifier);
412      IDiscreteDoubleValueModifier linearModifier = ComparisonFactorModifierParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("LinearDiscreteDoubleValueModifier"));
413      if (linearModifier != null) ComparisonFactorModifierParameter.Value = linearModifier;
414      ParameterizeComparisonFactorModifiers();
415
416      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
417      islandQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
418      selectionPressureAnalyzer = new ValueAnalyzer();
419      islandSelectionPressureAnalyzer = new ValueAnalyzer();
420      successfulOffspringAnalyzer = new SuccessfulOffspringAnalyzer();
421      ParameterizeAnalyzers();
422      UpdateAnalyzers();
423
424      Initialize();
425    }
426    public override void Prepare() {
427      if (Problem != null) base.Prepare();
428    }
429
430    #region Events
431    protected override void OnProblemChanged() {
432      ParameterizeStochasticOperator(Problem.SolutionCreator);
433      ParameterizeStochasticOperator(Problem.Evaluator);
434      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
435      ParameterizeSolutionsCreator();
436      ParameterizeMainLoop();
437      ParameterizeSelectors();
438      ParameterizeAnalyzers();
439      ParameterizeIterationBasedOperators();
440      UpdateCrossovers();
441      UpdateMutators();
442      UpdateAnalyzers();
443      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
444      base.OnProblemChanged();
445    }
446
447    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
448      ParameterizeStochasticOperator(Problem.SolutionCreator);
449      ParameterizeSolutionsCreator();
450      base.Problem_SolutionCreatorChanged(sender, e);
451    }
452    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
453      ParameterizeStochasticOperator(Problem.Evaluator);
454      ParameterizeSolutionsCreator();
455      ParameterizeMainLoop();
456      ParameterizeSelectors();
457      ParameterizeAnalyzers();
458      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
459      base.Problem_EvaluatorChanged(sender, e);
460    }
461    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
462      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
463      ParameterizeIterationBasedOperators();
464      UpdateCrossovers();
465      UpdateMutators();
466      UpdateAnalyzers();
467      base.Problem_OperatorsChanged(sender, e);
468    }
469    protected virtual void ElitesParameter_ValueChanged(object sender, EventArgs e) {
470      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
471      ParameterizeSelectors();
472    }
473    protected virtual void Elites_ValueChanged(object sender, EventArgs e) {
474      ParameterizeSelectors();
475    }
476    protected virtual void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
477      NumberOfIslands.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
478      ParameterizeSelectors();
479    }
480    protected virtual void PopulationSize_ValueChanged(object sender, EventArgs e) {
481      ParameterizeSelectors();
482    }
483    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
484      ParameterizeMainLoop();
485      ParameterizeSelectors();
486      ParameterizeAnalyzers();
487    }
488    protected virtual void MigrationRateParameter_ValueChanged(object sender, EventArgs e) {
489      MigrationRate.ValueChanged += new EventHandler(MigrationRate_ValueChanged);
490      ParameterizeSelectors();
491    }
492    protected virtual void MigrationRate_ValueChanged(object sender, EventArgs e) {
493      ParameterizeSelectors();
494    }
495    protected virtual void MaximumMigrationsParameter_ValueChanged(object sender, EventArgs e) {
496      MaximumGenerations.ValueChanged += new EventHandler(MaximumMigrations_ValueChanged);
497      ParameterizeComparisonFactorModifiers();
498    }
499    protected virtual void MaximumMigrations_ValueChanged(object sender, EventArgs e) {
500      ParameterizeComparisonFactorModifiers();
501    }
502    protected virtual void MigrationIntervalParameter_ValueChanged(object sender, EventArgs e) {
503      MigrationInterval.ValueChanged += new EventHandler(MigrationInterval_ValueChanged);
504      ParameterizeComparisonFactorModifiers();
505    }
506    protected virtual void MigrationInterval_ValueChanged(object sender, EventArgs e) {
507      ParameterizeComparisonFactorModifiers();
508    }
509    #endregion
510
511    #region Helpers
512    private void Initialize() {
513      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
514      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
515      MigrationRateParameter.ValueChanged += new EventHandler(MigrationRateParameter_ValueChanged);
516      MigrationRate.ValueChanged += new EventHandler(MigrationRate_ValueChanged);
517      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
518      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
519      MigrationIntervalParameter.ValueChanged += new EventHandler(MigrationIntervalParameter_ValueChanged);
520      MigrationInterval.ValueChanged += new EventHandler(MigrationInterval_ValueChanged);
521      MaximumGenerationsParameter.ValueChanged += new EventHandler(MaximumMigrationsParameter_ValueChanged);
522      MaximumGenerations.ValueChanged += new EventHandler(MaximumMigrations_ValueChanged);
523      if (Problem != null) {
524        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
525      }
526    }
527    protected virtual void ParameterizeSolutionsCreator() {
528      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
529      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
530    }
531    protected virtual void ParameterizeMainLoop() {
532      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
533      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
534      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
535      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
536    }
537    protected virtual void ParameterizeStochasticOperator(IOperator op) {
538      if (op is IStochasticOperator)
539        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
540    }
541    protected virtual void ParameterizeSelectors() {
542      foreach (ISelector selector in SelectorParameter.ValidValues) {
543        selector.CopySelected = new BoolValue(true);
544        selector.NumberOfSelectedSubScopesParameter.Value = null;
545        selector.NumberOfSelectedSubScopesParameter.ActualName = SelectedParentsParameter.Name;
546        ParameterizeStochasticOperator(selector);
547      }
548      foreach (ISelector selector in EmigrantsSelectorParameter.ValidValues) {
549        selector.CopySelected = new BoolValue(true);
550        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue((int)Math.Ceiling(PopulationSize.Value * MigrationRate.Value));
551        ParameterizeStochasticOperator(selector);
552      }
553      foreach (IReplacer selector in ImmigrationReplacerParameter.ValidValues) {
554        ParameterizeStochasticOperator(selector);
555      }
556      if (Problem != null) {
557        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
558          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
559          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
560        }
561        foreach (ISingleObjectiveSelector selector in EmigrantsSelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
562          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
563          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
564        }
565        foreach (ISingleObjectiveReplacer replacer in ImmigrationReplacerParameter.ValidValues.OfType<ISingleObjectiveReplacer>()) {
566          replacer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
567          replacer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
568        }
569      }
570    }
571    protected virtual void ParameterizeAnalyzers() {
572      islandQualityAnalyzer.ResultsParameter.ActualName = "Results";
573      islandQualityAnalyzer.QualityParameter.Depth = 1;
574      qualityAnalyzer.ResultsParameter.ActualName = "Results";
575      qualityAnalyzer.QualityParameter.Depth = 2;
576
577      islandSelectionPressureAnalyzer.ResultsParameter.ActualName = "Results";
578      islandSelectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
579      islandSelectionPressureAnalyzer.ValueParameter.Depth = 0;
580      islandSelectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
581      islandSelectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
582
583      selectionPressureAnalyzer.ResultsParameter.ActualName = "Results";
584      selectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
585      selectionPressureAnalyzer.ValueParameter.Depth = 1;
586      selectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
587      selectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
588
589      successfulOffspringAnalyzer.ResultsParameter.ActualName = "Results";
590      successfulOffspringAnalyzer.GenerationsParameter.ActualName = "Generations";
591      successfulOffspringAnalyzer.SuccessfulOffspringFlagParameter.Value.Value = "SuccessfulOffspring";
592      successfulOffspringAnalyzer.DepthParameter.Value = new IntValue(2);
593
594      if (Problem != null) {
595        islandQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
596        islandQualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
597        islandQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
598
599        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
600        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
601        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
602      }
603    }
604    protected virtual void ParameterizeComparisonFactorModifiers() {
605      foreach (IDiscreteDoubleValueModifier modifier in ComparisonFactorModifierParameter.ValidValues) {
606        modifier.IndexParameter.ActualName = "Generations";
607        modifier.EndIndexParameter.Value = new IntValue(MigrationInterval.Value * MaximumGenerations.Value);
608        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
609        modifier.StartIndexParameter.Value = new IntValue(0);
610        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
611        modifier.ValueParameter.ActualName = "ComparisonFactor";
612      }
613    }
614    protected virtual void ParameterizeIterationBasedOperators() {
615      if (Problem != null) {
616        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
617          op.IterationsParameter.ActualName = "Generations";
618          op.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name;
619        }
620      }
621    }
622    protected virtual void UpdateCrossovers() {
623      ICrossover oldCrossover = CrossoverParameter.Value;
624      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
625      CrossoverParameter.ValidValues.Clear();
626      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
627        CrossoverParameter.ValidValues.Add(crossover);
628      if (oldCrossover != null) {
629        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
630        if (crossover != null) CrossoverParameter.Value = crossover;
631        else oldCrossover = null;
632      }
633      if (oldCrossover == null && defaultCrossover != null)
634        CrossoverParameter.Value = defaultCrossover;
635    }
636    protected virtual void UpdateMutators() {
637      IManipulator oldMutator = MutatorParameter.Value;
638      MutatorParameter.ValidValues.Clear();
639      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
640        MutatorParameter.ValidValues.Add(mutator);
641      if (oldMutator != null) {
642        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
643        if (mutator != null) MutatorParameter.Value = mutator;
644      }
645    }
646    private void UpdateAnalyzers() {
647      IslandAnalyzer.Operators.Clear();
648      Analyzer.Operators.Clear();
649      IslandAnalyzer.Operators.Add(islandQualityAnalyzer, islandQualityAnalyzer.EnabledByDefault);
650      IslandAnalyzer.Operators.Add(islandSelectionPressureAnalyzer, islandSelectionPressureAnalyzer.EnabledByDefault);
651      if (Problem != null) {
652        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
653          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
654            param.Depth = 2;
655          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
656        }
657      }
658      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
659      Analyzer.Operators.Add(selectionPressureAnalyzer, selectionPressureAnalyzer.EnabledByDefault);
660      Analyzer.Operators.Add(successfulOffspringAnalyzer, successfulOffspringAnalyzer.EnabledByDefault);
661    }
662    protected virtual IslandOffspringSelectionGeneticAlgorithmMainLoop FindMainLoop(IOperator start) {
663      IOperator mainLoop = start;
664      while (mainLoop != null && !(mainLoop is IslandOffspringSelectionGeneticAlgorithmMainLoop))
665        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
666      if (mainLoop == null) return null;
667      else return (IslandOffspringSelectionGeneticAlgorithmMainLoop)mainLoop;
668    }
669    #endregion
670  }
671}
Note: See TracBrowser for help on using the repository browser.