Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm/3.3/SASEGASA.cs @ 17198

Last change on this file since 17198 was 17198, checked in by mkommend, 5 years ago

#3020: Adapated AfterDeserializationHook of genetic algorithms to check if the mutator parameter already has the correct type.
In detail the following algorithms have been adapted: ALPS-GA, ALPS-OSGA, GA, Island-GA, NSGA-2, Island-OSGA, OSGA, SASEGASA.

File size: 34.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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 HEAL.Attic;
25using HeuristicLab.Analysis;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Operators;
30using HeuristicLab.Optimization;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
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  [StorableType("1A52C36E-DC73-4D42-88CC-249130E4D784")]
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(StorableConstructorFlag _) : base(_) { }
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      var mutatorParameter = MutatorParameter as ConstrainedValueParameter<IManipulator>;
261      if (mutatorParameter == null && optionalMutatorParameter != null) {
262        Parameters.Remove(optionalMutatorParameter);
263        Parameters.Add(new ConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
264        foreach (var m in optionalMutatorParameter.ValidValues)
265          MutatorParameter.ValidValues.Add(m);
266        if (optionalMutatorParameter.Value == null) MutationProbability.Value = 0; // to guarantee that the old configuration results in the same behavior
267        else Mutator = optionalMutatorParameter.Value;
268        optionalMutatorParameter.ValidValues.Clear(); // to avoid dangling references to the old parameter its valid values are cleared
269      }
270      #endregion
271
272      Initialize();
273    }
274    private SASEGASA(SASEGASA original, Cloner cloner)
275      : base(original, cloner) {
276      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
277      villageQualityAnalyzer = cloner.Clone(original.villageQualityAnalyzer);
278      selectionPressureAnalyzer = cloner.Clone(original.selectionPressureAnalyzer);
279      villageSelectionPressureAnalyzer = cloner.Clone(original.villageSelectionPressureAnalyzer);
280      successfulOffspringAnalyzer = cloner.Clone(original.successfulOffspringAnalyzer);
281      Initialize();
282    }
283    public override IDeepCloneable Clone(Cloner cloner) {
284      return new SASEGASA(this, cloner);
285    }
286    public SASEGASA()
287      : base() {
288      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
289      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
290      Parameters.Add(new ValueParameter<IntValue>("NumberOfVillages", "The initial number of villages.", new IntValue(10)));
291      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions.", new IntValue(100)));
292      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations that should be processed.", new IntValue(1000)));
293      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
294      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
295      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
296      Parameters.Add(new ConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
297      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
298      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 });
299      Parameters.Add(new ValueLookupParameter<DoubleValue>("SuccessRatio", "The ratio of successful to total children that should be achieved.", new DoubleValue(1)));
300      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactorLowerBound", "The lower bound of the comparison factor (start).", new DoubleValue(0.3)));
301      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactorUpperBound", "The upper bound of the comparison factor (end).", new DoubleValue(0.7)));
302      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("ComparisonFactorModifier", "The operator used to modify the comparison factor.", new ItemSet<IDiscreteDoubleValueModifier>(new IDiscreteDoubleValueModifier[] { new LinearDiscreteDoubleValueModifier() }), new LinearDiscreteDoubleValueModifier()));
303      Parameters.Add(new ValueLookupParameter<DoubleValue>("MaximumSelectionPressure", "The maximum selection pressure that terminates the algorithm.", new DoubleValue(100)));
304      Parameters.Add(new ValueLookupParameter<DoubleValue>("FinalMaximumSelectionPressure", "The maximum selection pressure used when there is only one village left.", new DoubleValue(100)));
305      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)));
306      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)));
307      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the villages.", new MultiAnalyzer()));
308      Parameters.Add(new ValueParameter<MultiAnalyzer>("VillageAnalyzer", "The operator used to analyze each village.", new MultiAnalyzer()));
309      Parameters.Add(new ValueParameter<IntValue>("MaximumEvaluatedSolutions", "The maximum number of evaluated solutions (approximately).", new IntValue(int.MaxValue)));
310      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 });
311
312      RandomCreator randomCreator = new RandomCreator();
313      SubScopesCreator populationCreator = new SubScopesCreator();
314      UniformSubScopesProcessor ussp1 = new UniformSubScopesProcessor();
315      SolutionsCreator solutionsCreator = new SolutionsCreator();
316      VariableCreator variableCreator = new VariableCreator();
317      UniformSubScopesProcessor ussp2 = new UniformSubScopesProcessor();
318      SubScopesCounter subScopesCounter = new SubScopesCounter();
319      ResultsCollector resultsCollector = new ResultsCollector();
320      SASEGASAMainLoop mainLoop = new SASEGASAMainLoop();
321      OperatorGraph.InitialOperator = randomCreator;
322
323      randomCreator.RandomParameter.ActualName = "Random";
324      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
325      randomCreator.SeedParameter.Value = null;
326      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
327      randomCreator.SetSeedRandomlyParameter.Value = null;
328      randomCreator.Successor = populationCreator;
329
330      populationCreator.NumberOfSubScopesParameter.ActualName = NumberOfVillagesParameter.Name;
331      populationCreator.Successor = ussp1;
332
333      ussp1.Operator = solutionsCreator;
334      ussp1.Successor = variableCreator;
335
336      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
337      solutionsCreator.Successor = null;
338
339      variableCreator.Name = "Initialize EvaluatedSolutions";
340      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue()));
341      variableCreator.Successor = ussp2;
342
343      ussp2.Operator = subScopesCounter;
344      ussp2.Successor = resultsCollector;
345
346      subScopesCounter.Name = "Increment EvaluatedSolutions";
347      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
348
349      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", "", "EvaluatedSolutions"));
350      resultsCollector.ResultsParameter.ActualName = "Results";
351      resultsCollector.Successor = mainLoop;
352
353      mainLoop.NumberOfVillagesParameter.ActualName = NumberOfVillagesParameter.Name;
354      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
355      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
356      mainLoop.ElitesParameter.ActualName = ElitesParameter.Name;
357      mainLoop.ReevaluateElitesParameter.ActualName = ReevaluateElitesParameter.Name;
358      mainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
359      mainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
360      mainLoop.RandomParameter.ActualName = randomCreator.RandomParameter.ActualName;
361      mainLoop.ResultsParameter.ActualName = "Results";
362      mainLoop.SuccessRatioParameter.ActualName = SuccessRatioParameter.Name;
363      mainLoop.ComparisonFactorStartParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
364      mainLoop.ComparisonFactorModifierParameter.ActualName = ComparisonFactorModifierParameter.Name;
365      mainLoop.MaximumSelectionPressureParameter.ActualName = MaximumSelectionPressureParameter.Name;
366      mainLoop.FinalMaximumSelectionPressureParameter.ActualName = FinalMaximumSelectionPressureParameter.Name;
367      mainLoop.MaximumGenerationsParameter.ActualName = MaximumGenerationsParameter.Name;
368      mainLoop.OffspringSelectionBeforeMutationParameter.ActualName = OffspringSelectionBeforeMutationParameter.Name;
369      mainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
370      mainLoop.FillPopulationWithParentsParameter.ActualName = FillPopulationWithParentsParameter.Name;
371      mainLoop.Successor = null;
372
373      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is IMultiObjectiveSelector)).OrderBy(x => x.Name))
374        SelectorParameter.ValidValues.Add(selector);
375      ISelector proportionalSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("ProportionalSelector"));
376      if (proportionalSelector != null) SelectorParameter.Value = proportionalSelector;
377
378      ParameterizeSelectors();
379
380      foreach (IDiscreteDoubleValueModifier modifier in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name))
381        ComparisonFactorModifierParameter.ValidValues.Add(modifier);
382      IDiscreteDoubleValueModifier linearModifier = ComparisonFactorModifierParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("LinearDiscreteDoubleValueModifier"));
383      if (linearModifier != null) ComparisonFactorModifierParameter.Value = linearModifier;
384      ParameterizeComparisonFactorModifiers();
385
386      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
387      villageQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
388      selectionPressureAnalyzer = new ValueAnalyzer();
389      villageSelectionPressureAnalyzer = new ValueAnalyzer();
390      successfulOffspringAnalyzer = new SuccessfulOffspringAnalyzer();
391      ParameterizeAnalyzers();
392      UpdateAnalyzers();
393
394      Initialize();
395    }
396
397    public override void Prepare() {
398      if (Problem != null) base.Prepare();
399    }
400
401    #region Events
402    protected override void OnProblemChanged() {
403      ParameterizeStochasticOperator(Problem.SolutionCreator);
404      ParameterizeStochasticOperator(Problem.Evaluator);
405      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
406      ParameterizeSolutionsCreator();
407      ParameterizeMainLoop();
408      ParameterizeSelectors();
409      ParameterizeAnalyzers();
410      ParameterizeIterationBasedOperators();
411      UpdateCrossovers();
412      UpdateMutators();
413      UpdateAnalyzers();
414      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
415      base.OnProblemChanged();
416    }
417
418    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
419      ParameterizeStochasticOperator(Problem.SolutionCreator);
420      ParameterizeSolutionsCreator();
421      base.Problem_SolutionCreatorChanged(sender, e);
422    }
423    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
424      ParameterizeStochasticOperator(Problem.Evaluator);
425      ParameterizeSolutionsCreator();
426      ParameterizeMainLoop();
427      ParameterizeSelectors();
428      ParameterizeAnalyzers();
429      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
430      base.Problem_EvaluatorChanged(sender, e);
431    }
432    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
433      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
434      ParameterizeIterationBasedOperators();
435      UpdateCrossovers();
436      UpdateMutators();
437      UpdateAnalyzers();
438      base.Problem_OperatorsChanged(sender, e);
439    }
440    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
441      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
442      ParameterizeSelectors();
443    }
444    private void Elites_ValueChanged(object sender, EventArgs e) {
445      ParameterizeSelectors();
446    }
447    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
448      NumberOfVillages.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
449      ParameterizeSelectors();
450    }
451    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
452      ParameterizeSelectors();
453    }
454    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
455      ParameterizeMainLoop();
456      ParameterizeSelectors();
457      ParameterizeAnalyzers();
458    }
459    private void MaximumGenerationsParameter_ValueChanged(object sender, EventArgs e) {
460      MaximumGenerations.ValueChanged += new EventHandler(MaximumGenerations_ValueChanged);
461      MaximumGenerations_ValueChanged(sender, e);
462    }
463    private void MaximumGenerations_ValueChanged(object sender, EventArgs e) {
464      if (MaximumGenerations.Value < NumberOfVillages.Value) NumberOfVillages.Value = MaximumGenerations.Value;
465      ParameterizeMainLoop();
466    }
467    private void NumberOfVillagesParameter_ValueChanged(object sender, EventArgs e) {
468      NumberOfVillages.ValueChanged += new EventHandler(NumberOfVillages_ValueChanged);
469      NumberOfVillages_ValueChanged(sender, e);
470    }
471    private void NumberOfVillages_ValueChanged(object sender, EventArgs e) {
472      if (NumberOfVillages.Value > MaximumGenerations.Value) MaximumGenerations.Value = NumberOfVillages.Value;
473      ParameterizeComparisonFactorModifiers();
474      ParameterizeMainLoop();
475    }
476    #endregion
477
478    #region Helpers
479    private void Initialize() {
480      NumberOfVillagesParameter.ValueChanged += new EventHandler(NumberOfVillagesParameter_ValueChanged);
481      NumberOfVillages.ValueChanged += new EventHandler(NumberOfVillages_ValueChanged);
482      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
483      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
484      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
485      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
486      MaximumGenerationsParameter.ValueChanged += new EventHandler(MaximumGenerationsParameter_ValueChanged);
487      MaximumGenerations.ValueChanged += new EventHandler(MaximumGenerations_ValueChanged);
488      if (Problem != null) {
489        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
490      }
491    }
492    private void ParameterizeSolutionsCreator() {
493      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
494      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
495    }
496    private void ParameterizeMainLoop() {
497      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
498      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
499      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
500      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
501      MainLoop.MigrationIntervalParameter.Value = new IntValue(MaximumGenerations.Value / NumberOfVillages.Value);
502    }
503    private void ParameterizeStochasticOperator(IOperator op) {
504      if (op is IStochasticOperator)
505        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
506    }
507    private void ParameterizeSelectors() {
508      foreach (ISelector selector in SelectorParameter.ValidValues) {
509        selector.CopySelected = new BoolValue(true);
510        selector.NumberOfSelectedSubScopesParameter.Value = null;
511        selector.NumberOfSelectedSubScopesParameter.ActualName = SelectedParentsParameter.Name;
512        ParameterizeStochasticOperator(selector);
513      }
514      if (Problem != null) {
515        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
516          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
517          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
518        }
519      }
520    }
521    private void ParameterizeAnalyzers() {
522      villageQualityAnalyzer.ResultsParameter.ActualName = "Results";
523      villageQualityAnalyzer.QualityParameter.Depth = 1;
524      qualityAnalyzer.ResultsParameter.ActualName = "Results";
525      qualityAnalyzer.QualityParameter.Depth = 2;
526
527      villageSelectionPressureAnalyzer.ResultsParameter.ActualName = "Results";
528      villageSelectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
529      villageSelectionPressureAnalyzer.ValueParameter.Depth = 0;
530      villageSelectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
531      villageSelectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
532
533      selectionPressureAnalyzer.ResultsParameter.ActualName = "Results";
534      selectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
535      selectionPressureAnalyzer.ValueParameter.Depth = 1;
536      selectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
537      selectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
538
539      successfulOffspringAnalyzer.ResultsParameter.ActualName = "Results";
540      successfulOffspringAnalyzer.GenerationsParameter.ActualName = "Generations";
541      successfulOffspringAnalyzer.SuccessfulOffspringFlagParameter.Value.Value = "SuccessfulOffspring";
542      successfulOffspringAnalyzer.DepthParameter.Value = new IntValue(2);
543
544      if (Problem != null) {
545        villageQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
546        villageQualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
547        villageQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
548
549        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
550        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
551        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
552      }
553    }
554    private void ParameterizeComparisonFactorModifiers() {
555      foreach (IDiscreteDoubleValueModifier modifier in ComparisonFactorModifierParameter.ValidValues) {
556        modifier.IndexParameter.ActualName = "Reunifications";
557        modifier.StartIndexParameter.Value = new IntValue(0);
558        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
559        modifier.EndIndexParameter.Value = new IntValue(NumberOfVillages.Value - 1);
560        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
561        modifier.ValueParameter.ActualName = "ComparisonFactor";
562      }
563    }
564    private void ParameterizeIterationBasedOperators() {
565      if (Problem != null) {
566        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
567          op.IterationsParameter.ActualName = "Generations";
568          op.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name;
569        }
570      }
571    }
572    private void UpdateCrossovers() {
573      ICrossover oldCrossover = CrossoverParameter.Value;
574      CrossoverParameter.ValidValues.Clear();
575      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
576
577      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
578        CrossoverParameter.ValidValues.Add(crossover);
579
580      if (oldCrossover != null) {
581        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
582        if (crossover != null) CrossoverParameter.Value = crossover;
583        else oldCrossover = null;
584      }
585      if (oldCrossover == null && defaultCrossover != null)
586        CrossoverParameter.Value = defaultCrossover;
587    }
588    private void UpdateMutators() {
589      IManipulator oldMutator = MutatorParameter.Value;
590      MutatorParameter.ValidValues.Clear();
591      IManipulator defaultMutator = Problem.Operators.OfType<IManipulator>().FirstOrDefault();
592
593      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
594        MutatorParameter.ValidValues.Add(mutator);
595
596      if (oldMutator != null) {
597        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
598        if (mutator != null) MutatorParameter.Value = mutator;
599        else oldMutator = null;
600      }
601
602      if (oldMutator == null && defaultMutator != null)
603        MutatorParameter.Value = defaultMutator;
604    }
605    private void UpdateAnalyzers() {
606      VillageAnalyzer.Operators.Clear();
607      Analyzer.Operators.Clear();
608      VillageAnalyzer.Operators.Add(villageQualityAnalyzer, villageQualityAnalyzer.EnabledByDefault);
609      VillageAnalyzer.Operators.Add(villageSelectionPressureAnalyzer, villageSelectionPressureAnalyzer.EnabledByDefault);
610      if (Problem != null) {
611        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
612          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
613            param.Depth = 2;
614          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
615        }
616      }
617      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
618      Analyzer.Operators.Add(selectionPressureAnalyzer, selectionPressureAnalyzer.EnabledByDefault);
619      Analyzer.Operators.Add(successfulOffspringAnalyzer, successfulOffspringAnalyzer.EnabledByDefault);
620    }
621    private SASEGASAMainLoop FindMainLoop(IOperator start) {
622      IOperator mainLoop = start;
623      while (mainLoop != null && !(mainLoop is SASEGASAMainLoop))
624        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
625      if (mainLoop == null) return null;
626      else return (SASEGASAMainLoop)mainLoop;
627    }
628    #endregion
629  }
630}
Note: See TracBrowser for help on using the repository browser.