Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10155 was 10155, checked in by mkommend, 11 years ago

#1997: Added possibility to reevaluate immigrants to the IslandGA and IslandOSGA.

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