Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2845_EnhancedProgress/HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm/3.3/SASEGASA.cs @ 16317

Last change on this file since 16317 was 16311, checked in by pfleck, 6 years ago

#2845 Merged trunk changes into branch (15406-15681, 15683-16308)

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