Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 16003 was 11646, checked in by mkommend, 10 years ago

#1997: Merged trunk changes to data analysis island GA branch.

File size: 38.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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    private IFixedValueParameter<BoolValue> FillPopulationWithParentsParameter {
136      get { return (IFixedValueParameter<BoolValue>)Parameters["FillPopulationWithParents"]; }
137    }
138    protected IFixedValueParameter<BoolValue> ReevaluateImmigrantsParameter {
139      get { return (IFixedValueParameter<BoolValue>)Parameters["ReevaluateImmigrants"]; }
140    }
141    #endregion
142
143    #region Properties
144    public IntValue Seed {
145      get { return SeedParameter.Value; }
146      set { SeedParameter.Value = value; }
147    }
148    public BoolValue SetSeedRandomly {
149      get { return SetSeedRandomlyParameter.Value; }
150      set { SetSeedRandomlyParameter.Value = value; }
151    }
152    public IntValue NumberOfIslands {
153      get { return NumberOfIslandsParameter.Value; }
154      set { NumberOfIslandsParameter.Value = value; }
155    }
156    public IntValue MigrationInterval {
157      get { return MigrationIntervalParameter.Value; }
158      set { MigrationIntervalParameter.Value = value; }
159    }
160    public PercentValue MigrationRate {
161      get { return MigrationRateParameter.Value; }
162      set { MigrationRateParameter.Value = value; }
163    }
164    public IMigrator Migrator {
165      get { return MigratorParameter.Value; }
166      set { MigratorParameter.Value = value; }
167    }
168    public ISelector EmigrantsSelector {
169      get { return EmigrantsSelectorParameter.Value; }
170      set { EmigrantsSelectorParameter.Value = value; }
171    }
172    public IReplacer ImmigrationReplacer {
173      get { return ImmigrationReplacerParameter.Value; }
174      set { ImmigrationReplacerParameter.Value = value; }
175    }
176    public IntValue PopulationSize {
177      get { return PopulationSizeParameter.Value; }
178      set { PopulationSizeParameter.Value = value; }
179    }
180    public IntValue MaximumGenerations {
181      get { return MaximumGenerationsParameter.Value; }
182      set { MaximumGenerationsParameter.Value = value; }
183    }
184    public ISelector Selector {
185      get { return SelectorParameter.Value; }
186      set { SelectorParameter.Value = value; }
187    }
188    public ICrossover Crossover {
189      get { return CrossoverParameter.Value; }
190      set { CrossoverParameter.Value = value; }
191    }
192    public PercentValue MutationProbability {
193      get { return MutationProbabilityParameter.Value; }
194      set { MutationProbabilityParameter.Value = value; }
195    }
196    public IManipulator Mutator {
197      get { return MutatorParameter.Value; }
198      set { MutatorParameter.Value = value; }
199    }
200    public IntValue Elites {
201      get { return ElitesParameter.Value; }
202      set { ElitesParameter.Value = value; }
203    }
204    public bool ReevaluteElites {
205      get { return ReevaluateElitesParameter.Value.Value; }
206      set { ReevaluateElitesParameter.Value.Value = value; }
207    }
208    public DoubleValue SuccessRatio {
209      get { return SuccessRatioParameter.Value; }
210      private set { SuccessRatioParameter.Value = value; }
211    }
212    public DoubleValue ComparisonFactorLowerBound {
213      get { return ComparisonFactorLowerBoundParameter.Value; }
214      private set { ComparisonFactorLowerBoundParameter.Value = value; }
215    }
216    public DoubleValue ComparisonFactorUpperBound {
217      get { return ComparisonFactorUpperBoundParameter.Value; }
218      private set { ComparisonFactorUpperBoundParameter.Value = value; }
219    }
220    public IDiscreteDoubleValueModifier ComparisonFactorModifier {
221      get { return ComparisonFactorModifierParameter.Value; }
222      set { ComparisonFactorModifierParameter.Value = value; }
223    }
224    public DoubleValue MaximumSelectionPressure {
225      get { return MaximumSelectionPressureParameter.Value; }
226      private set { MaximumSelectionPressureParameter.Value = value; }
227    }
228    public BoolValue OffspringSelectionBeforeMutation {
229      get { return OffspringSelectionBeforeMutationParameter.Value; }
230      private set { OffspringSelectionBeforeMutationParameter.Value = value; }
231    }
232    public MultiAnalyzer Analyzer {
233      get { return AnalyzerParameter.Value; }
234      set { AnalyzerParameter.Value = value; }
235    }
236    public MultiAnalyzer IslandAnalyzer {
237      get { return IslandAnalyzerParameter.Value; }
238      set { IslandAnalyzerParameter.Value = value; }
239    }
240    public IntValue MaximumEvaluatedSolutions {
241      get { return MaximumEvaluatedSolutionsParameter.Value; }
242      set { MaximumEvaluatedSolutionsParameter.Value = value; }
243    }
244    public bool FillPopulationWithParents {
245      get { return FillPopulationWithParentsParameter.Value.Value; }
246      set { FillPopulationWithParentsParameter.Value.Value = value; }
247    }
248    public bool ReevaluateImmigrants {
249      get { return ReevaluateImmigrantsParameter.Value.Value; }
250      set { ReevaluateImmigrantsParameter.Value.Value = value; }
251    }
252    protected RandomCreator RandomCreator {
253      get { return (RandomCreator)OperatorGraph.InitialOperator; }
254    }
255    protected UniformSubScopesProcessor IslandProcessor {
256      get { return OperatorGraph.Iterate().OfType<UniformSubScopesProcessor>().First(x => x.Operator is SolutionsCreator); }
257    }
258    protected SolutionsCreator SolutionsCreator {
259      get { return (SolutionsCreator)IslandProcessor.Operator; }
260    }
261    protected IslandOffspringSelectionGeneticAlgorithmMainLoop MainLoop {
262      get { return FindMainLoop(IslandProcessor.Successor); }
263    }
264    [Storable]
265    private BestAverageWorstQualityAnalyzer islandQualityAnalyzer;
266    [Storable]
267    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
268    [Storable]
269    private ValueAnalyzer islandSelectionPressureAnalyzer;
270    [Storable]
271    private ValueAnalyzer selectionPressureAnalyzer;
272    [Storable]
273    private SuccessfulOffspringAnalyzer successfulOffspringAnalyzer;
274    #endregion
275
276    [StorableConstructor]
277    protected IslandOffspringSelectionGeneticAlgorithm(bool deserializing) : base(deserializing) { }
278    [StorableHook(HookType.AfterDeserialization)]
279    private void AfterDeserialization() {
280      // BackwardsCompatibility3.3
281      #region Backwards compatible code, remove with 3.4
282      if (successfulOffspringAnalyzer == null)
283        successfulOffspringAnalyzer = new SuccessfulOffspringAnalyzer();
284      if (!Parameters.ContainsKey("ReevaluateElites")) {
285        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 });
286      }
287      if (!Parameters.ContainsKey("ReevaluateImmigrants")) {
288        Parameters.Add(new FixedValueParameter<BoolValue>("ReevaluateImmigrants", "Flag which indicates if inviduals should be reevaluated before they are immigrated.", new BoolValue(false)) { Hidden = true });
289      }
290      if (!Parameters.ContainsKey("FillPopulationWithParents"))
291        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 });
292      #endregion
293
294      Initialize();
295    }
296    protected IslandOffspringSelectionGeneticAlgorithm(IslandOffspringSelectionGeneticAlgorithm original, Cloner cloner)
297      : base(original, cloner) {
298      islandQualityAnalyzer = cloner.Clone(original.islandQualityAnalyzer);
299      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
300      islandSelectionPressureAnalyzer = cloner.Clone(original.islandSelectionPressureAnalyzer);
301      selectionPressureAnalyzer = cloner.Clone(original.selectionPressureAnalyzer);
302      successfulOffspringAnalyzer = cloner.Clone(original.successfulOffspringAnalyzer);
303      Initialize();
304    }
305    public override IDeepCloneable Clone(Cloner cloner) {
306      return new IslandOffspringSelectionGeneticAlgorithm(this, cloner);
307    }
308    public IslandOffspringSelectionGeneticAlgorithm()
309      : base() {
310      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
311      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
312      Parameters.Add(new ValueParameter<IntValue>("NumberOfIslands", "The number of islands.", new IntValue(5)));
313      Parameters.Add(new ValueParameter<IntValue>("MigrationInterval", "The number of generations that should pass between migration phases.", new IntValue(20)));
314      Parameters.Add(new ValueParameter<PercentValue>("MigrationRate", "The proportion of individuals that should migrate between the islands.", new PercentValue(0.15)));
315      Parameters.Add(new ConstrainedValueParameter<IMigrator>("Migrator", "The migration strategy."));
316      Parameters.Add(new ConstrainedValueParameter<ISelector>("EmigrantsSelector", "Selects the individuals that will be migrated."));
317      Parameters.Add(new ConstrainedValueParameter<IReplacer>("ImmigrationReplacer", "Replaces part of the original population with the immigrants."));
318      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions of each island.", new IntValue(100)));
319      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations that should be processed.", new IntValue(100)));
320      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
321      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
322      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
323      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
324      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
325      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 });
326      Parameters.Add(new ValueLookupParameter<DoubleValue>("SuccessRatio", "The ratio of successful to total children that should be achieved.", new DoubleValue(1)));
327      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactorLowerBound", "The lower bound of the comparison factor (start).", new DoubleValue(0)));
328      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactorUpperBound", "The upper bound of the comparison factor (end).", new DoubleValue(1)));
329      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("ComparisonFactorModifier", "The operator used to modify the comparison factor.", new ItemSet<IDiscreteDoubleValueModifier>(new IDiscreteDoubleValueModifier[] { new LinearDiscreteDoubleValueModifier() }), new LinearDiscreteDoubleValueModifier()));
330      Parameters.Add(new ValueLookupParameter<DoubleValue>("MaximumSelectionPressure", "The maximum selection pressure that terminates the algorithm.", new DoubleValue(100)));
331      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)));
332      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)));
333      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the islands.", new MultiAnalyzer()));
334      Parameters.Add(new ValueParameter<MultiAnalyzer>("IslandAnalyzer", "The operator used to analyze each island.", new MultiAnalyzer()));
335      Parameters.Add(new ValueParameter<IntValue>("MaximumEvaluatedSolutions", "The maximum number of evaluated solutions (approximately).", new IntValue(int.MaxValue)));
336      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 });
337      Parameters.Add(new FixedValueParameter<BoolValue>("ReevaluateImmigrants", "Flag which indicates if inviduals should be reevaluated before they are immigrated.", new BoolValue(false)) { 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        MigratorParameter.ValidValues.Add(migrator);
420
421      foreach (IDiscreteDoubleValueModifier modifier in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name))
422        ComparisonFactorModifierParameter.ValidValues.Add(modifier);
423      IDiscreteDoubleValueModifier linearModifier = ComparisonFactorModifierParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("LinearDiscreteDoubleValueModifier"));
424      if (linearModifier != null) ComparisonFactorModifierParameter.Value = linearModifier;
425      ParameterizeComparisonFactorModifiers();
426
427      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
428      islandQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
429      selectionPressureAnalyzer = new ValueAnalyzer();
430      islandSelectionPressureAnalyzer = new ValueAnalyzer();
431      successfulOffspringAnalyzer = new SuccessfulOffspringAnalyzer();
432      ParameterizeAnalyzers();
433      UpdateAnalyzers();
434
435      Initialize();
436    }
437    public override void Prepare() {
438      if (Problem != null) base.Prepare();
439    }
440
441    #region Events
442    protected override void OnProblemChanged() {
443      ParameterizeStochasticOperator(Problem.SolutionCreator);
444      ParameterizeStochasticOperator(Problem.Evaluator);
445      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
446      ParameterizeSolutionsCreator();
447      ParameterizeMainLoop();
448      ParameterizeSelectors();
449      ParameterizeAnalyzers();
450      ParameterizeIterationBasedOperators();
451      UpdateCrossovers();
452      UpdateMutators();
453      UpdateAnalyzers();
454      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
455      base.OnProblemChanged();
456    }
457
458    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
459      ParameterizeStochasticOperator(Problem.SolutionCreator);
460      ParameterizeSolutionsCreator();
461      base.Problem_SolutionCreatorChanged(sender, e);
462    }
463    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
464      ParameterizeStochasticOperator(Problem.Evaluator);
465      ParameterizeSolutionsCreator();
466      ParameterizeMainLoop();
467      ParameterizeSelectors();
468      ParameterizeAnalyzers();
469      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
470      base.Problem_EvaluatorChanged(sender, e);
471    }
472    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
473      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
474      ParameterizeIterationBasedOperators();
475      UpdateCrossovers();
476      UpdateMutators();
477      UpdateAnalyzers();
478      base.Problem_OperatorsChanged(sender, e);
479    }
480    protected virtual void ElitesParameter_ValueChanged(object sender, EventArgs e) {
481      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
482      ParameterizeSelectors();
483    }
484    protected virtual void Elites_ValueChanged(object sender, EventArgs e) {
485      ParameterizeSelectors();
486    }
487    protected virtual void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
488      NumberOfIslands.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
489      ParameterizeSelectors();
490    }
491    protected virtual void PopulationSize_ValueChanged(object sender, EventArgs e) {
492      ParameterizeSelectors();
493    }
494    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
495      ParameterizeMainLoop();
496      ParameterizeSelectors();
497      ParameterizeAnalyzers();
498    }
499    protected virtual void MigrationRateParameter_ValueChanged(object sender, EventArgs e) {
500      MigrationRate.ValueChanged += new EventHandler(MigrationRate_ValueChanged);
501      ParameterizeSelectors();
502    }
503    protected virtual void MigrationRate_ValueChanged(object sender, EventArgs e) {
504      ParameterizeSelectors();
505    }
506    protected virtual void MaximumMigrationsParameter_ValueChanged(object sender, EventArgs e) {
507      MaximumGenerations.ValueChanged += new EventHandler(MaximumMigrations_ValueChanged);
508      ParameterizeComparisonFactorModifiers();
509    }
510    protected virtual void MaximumMigrations_ValueChanged(object sender, EventArgs e) {
511      ParameterizeComparisonFactorModifiers();
512    }
513    protected virtual void MigrationIntervalParameter_ValueChanged(object sender, EventArgs e) {
514      MigrationInterval.ValueChanged += new EventHandler(MigrationInterval_ValueChanged);
515      ParameterizeComparisonFactorModifiers();
516    }
517    protected virtual void MigrationInterval_ValueChanged(object sender, EventArgs e) {
518      ParameterizeComparisonFactorModifiers();
519    }
520    #endregion
521
522    #region Helpers
523    private void Initialize() {
524      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
525      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
526      MigrationRateParameter.ValueChanged += new EventHandler(MigrationRateParameter_ValueChanged);
527      MigrationRate.ValueChanged += new EventHandler(MigrationRate_ValueChanged);
528      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
529      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
530      MigrationIntervalParameter.ValueChanged += new EventHandler(MigrationIntervalParameter_ValueChanged);
531      MigrationInterval.ValueChanged += new EventHandler(MigrationInterval_ValueChanged);
532      MaximumGenerationsParameter.ValueChanged += new EventHandler(MaximumMigrationsParameter_ValueChanged);
533      MaximumGenerations.ValueChanged += new EventHandler(MaximumMigrations_ValueChanged);
534      if (Problem != null) {
535        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
536      }
537    }
538    protected virtual void ParameterizeSolutionsCreator() {
539      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
540      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
541    }
542    protected virtual void ParameterizeMainLoop() {
543      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
544      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
545      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
546      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
547    }
548    protected virtual void ParameterizeStochasticOperator(IOperator op) {
549      if (op is IStochasticOperator)
550        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
551    }
552    protected virtual void ParameterizeSelectors() {
553      foreach (ISelector selector in SelectorParameter.ValidValues) {
554        selector.CopySelected = new BoolValue(true);
555        selector.NumberOfSelectedSubScopesParameter.Value = null;
556        selector.NumberOfSelectedSubScopesParameter.ActualName = SelectedParentsParameter.Name;
557        ParameterizeStochasticOperator(selector);
558      }
559      foreach (ISelector selector in EmigrantsSelectorParameter.ValidValues) {
560        selector.CopySelected = new BoolValue(true);
561        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue((int)Math.Ceiling(PopulationSize.Value * MigrationRate.Value));
562        ParameterizeStochasticOperator(selector);
563      }
564      foreach (IReplacer selector in ImmigrationReplacerParameter.ValidValues) {
565        ParameterizeStochasticOperator(selector);
566      }
567      if (Problem != null) {
568        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
569          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
570          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
571        }
572        foreach (ISingleObjectiveSelector selector in EmigrantsSelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
573          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
574          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
575        }
576        foreach (ISingleObjectiveReplacer replacer in ImmigrationReplacerParameter.ValidValues.OfType<ISingleObjectiveReplacer>()) {
577          replacer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
578          replacer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
579        }
580      }
581    }
582    protected virtual void ParameterizeAnalyzers() {
583      islandQualityAnalyzer.ResultsParameter.ActualName = "Results";
584      islandQualityAnalyzer.QualityParameter.Depth = 1;
585      qualityAnalyzer.ResultsParameter.ActualName = "Results";
586      qualityAnalyzer.QualityParameter.Depth = 2;
587
588      islandSelectionPressureAnalyzer.ResultsParameter.ActualName = "Results";
589      islandSelectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
590      islandSelectionPressureAnalyzer.ValueParameter.Depth = 0;
591      islandSelectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
592      islandSelectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
593
594      selectionPressureAnalyzer.ResultsParameter.ActualName = "Results";
595      selectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
596      selectionPressureAnalyzer.ValueParameter.Depth = 1;
597      selectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
598      selectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
599
600      successfulOffspringAnalyzer.ResultsParameter.ActualName = "Results";
601      successfulOffspringAnalyzer.GenerationsParameter.ActualName = "Generations";
602      successfulOffspringAnalyzer.SuccessfulOffspringFlagParameter.Value.Value = "SuccessfulOffspring";
603      successfulOffspringAnalyzer.DepthParameter.Value = new IntValue(2);
604
605      if (Problem != null) {
606        islandQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
607        islandQualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
608        islandQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
609
610        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
611        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
612        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
613      }
614    }
615    protected virtual void ParameterizeComparisonFactorModifiers() {
616      foreach (IDiscreteDoubleValueModifier modifier in ComparisonFactorModifierParameter.ValidValues) {
617        modifier.IndexParameter.ActualName = "Generations";
618        modifier.EndIndexParameter.Value = new IntValue(MigrationInterval.Value * MaximumGenerations.Value);
619        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
620        modifier.StartIndexParameter.Value = new IntValue(0);
621        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
622        modifier.ValueParameter.ActualName = "ComparisonFactor";
623      }
624    }
625    protected virtual void ParameterizeIterationBasedOperators() {
626      if (Problem != null) {
627        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
628          op.IterationsParameter.ActualName = "Generations";
629          op.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name;
630        }
631      }
632    }
633    protected virtual void UpdateCrossovers() {
634      ICrossover oldCrossover = CrossoverParameter.Value;
635      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
636      CrossoverParameter.ValidValues.Clear();
637      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
638        CrossoverParameter.ValidValues.Add(crossover);
639      if (oldCrossover != null) {
640        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
641        if (crossover != null) CrossoverParameter.Value = crossover;
642        else oldCrossover = null;
643      }
644      if (oldCrossover == null && defaultCrossover != null)
645        CrossoverParameter.Value = defaultCrossover;
646    }
647    protected virtual void UpdateMutators() {
648      IManipulator oldMutator = MutatorParameter.Value;
649      MutatorParameter.ValidValues.Clear();
650      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
651        MutatorParameter.ValidValues.Add(mutator);
652      if (oldMutator != null) {
653        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
654        if (mutator != null) MutatorParameter.Value = mutator;
655      }
656    }
657    private void UpdateAnalyzers() {
658      IslandAnalyzer.Operators.Clear();
659      Analyzer.Operators.Clear();
660      IslandAnalyzer.Operators.Add(islandQualityAnalyzer, islandQualityAnalyzer.EnabledByDefault);
661      IslandAnalyzer.Operators.Add(islandSelectionPressureAnalyzer, islandSelectionPressureAnalyzer.EnabledByDefault);
662      if (Problem != null) {
663        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
664          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
665            param.Depth = 2;
666          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
667        }
668      }
669      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
670      Analyzer.Operators.Add(selectionPressureAnalyzer, selectionPressureAnalyzer.EnabledByDefault);
671      Analyzer.Operators.Add(successfulOffspringAnalyzer, successfulOffspringAnalyzer.EnabledByDefault);
672    }
673    protected virtual IslandOffspringSelectionGeneticAlgorithmMainLoop FindMainLoop(IOperator start) {
674      IOperator mainLoop = start;
675      while (mainLoop != null && !(mainLoop is IslandOffspringSelectionGeneticAlgorithmMainLoop))
676        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
677      if (mainLoop == null) return null;
678      else return (IslandOffspringSelectionGeneticAlgorithmMainLoop)mainLoop;
679    }
680    #endregion
681  }
682}
Note: See TracBrowser for help on using the repository browser.