source: branches/TerminationCriteria/HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm/3.3/OffspringSelectionGeneticAlgorithm.cs @ 12411

Last change on this file since 12411 was 12411, checked in by pfleck, 4 years ago

#2027

  • Removed MaximumIterationsTerminator and MaximumEvaluatedSolutionsTermimator because they practically do the same.
  • Add the possibility for ThresholdTerminators to use a foreign parameter (e.g. MaximumSelectionPressure). This way the terminator can use parameters which are still relevant for the algorithm and still provide consistent management of the terminators.
  • Renamed IThresholdTerminator to ISingleValueTerminator.
File size: 32.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Collections.Generic;
24using System.Linq;
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.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.PluginInfrastructure;
35using HeuristicLab.Random;
36using HeuristicLab.Termination;
37
38namespace HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm {
39  /// <summary>
40  /// An offspring selection genetic algorithm.
41  /// </summary>
42  [Item("Offspring Selection Genetic Algorithm", "An offspring selection genetic algorithm (Affenzeller, M. et al. 2009. Genetic Algorithms and Genetic Programming - Modern Concepts and Practical Applications. CRC Press).")]
43  [Creatable("Algorithms")]
44  [StorableClass]
45  public sealed class OffspringSelectionGeneticAlgorithm : HeuristicOptimizationEngineAlgorithm, IStorableContent {
46    public string Filename { get; set; }
47
48    #region Problem Properties
49    public override Type ProblemType {
50      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
51    }
52    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
53      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
54      set { base.Problem = value; }
55    }
56    #endregion
57
58    #region Parameter Properties
59    private ValueParameter<IntValue> SeedParameter {
60      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
61    }
62    private ValueParameter<BoolValue> SetSeedRandomlyParameter {
63      get { return (ValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
64    }
65    private ValueParameter<IntValue> PopulationSizeParameter {
66      get { return (ValueParameter<IntValue>)Parameters["PopulationSize"]; }
67    }
68    public IConstrainedValueParameter<ISelector> SelectorParameter {
69      get { return (IConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
70    }
71    public IConstrainedValueParameter<ICrossover> CrossoverParameter {
72      get { return (IConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
73    }
74    private ValueParameter<PercentValue> MutationProbabilityParameter {
75      get { return (ValueParameter<PercentValue>)Parameters["MutationProbability"]; }
76    }
77    public IConstrainedValueParameter<IManipulator> MutatorParameter {
78      get { return (IConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
79    }
80    private ValueParameter<IntValue> ElitesParameter {
81      get { return (ValueParameter<IntValue>)Parameters["Elites"]; }
82    }
83    private IFixedValueParameter<BoolValue> ReevaluateElitesParameter {
84      get { return (IFixedValueParameter<BoolValue>)Parameters["ReevaluateElites"]; }
85    }
86    private IFixedValueParameter<IntValue> MaximumGenerationsParameter {
87      get { return (IFixedValueParameter<IntValue>)Parameters["MaximumGenerations"]; }
88    }
89    private ValueLookupParameter<DoubleValue> SuccessRatioParameter {
90      get { return (ValueLookupParameter<DoubleValue>)Parameters["SuccessRatio"]; }
91    }
92    private ValueLookupParameter<DoubleValue> ComparisonFactorLowerBoundParameter {
93      get { return (ValueLookupParameter<DoubleValue>)Parameters["ComparisonFactorLowerBound"]; }
94    }
95    private ValueLookupParameter<DoubleValue> ComparisonFactorUpperBoundParameter {
96      get { return (ValueLookupParameter<DoubleValue>)Parameters["ComparisonFactorUpperBound"]; }
97    }
98    public IConstrainedValueParameter<IDiscreteDoubleValueModifier> ComparisonFactorModifierParameter {
99      get { return (IConstrainedValueParameter<IDiscreteDoubleValueModifier>)Parameters["ComparisonFactorModifier"]; }
100    }
101    private ValueLookupParameter<DoubleValue> MaximumSelectionPressureParameter {
102      get { return (ValueLookupParameter<DoubleValue>)Parameters["MaximumSelectionPressure"]; }
103    }
104    private ValueLookupParameter<BoolValue> OffspringSelectionBeforeMutationParameter {
105      get { return (ValueLookupParameter<BoolValue>)Parameters["OffspringSelectionBeforeMutation"]; }
106    }
107    private ValueLookupParameter<IntValue> SelectedParentsParameter {
108      get { return (ValueLookupParameter<IntValue>)Parameters["SelectedParents"]; }
109    }
110    private ValueParameter<MultiAnalyzer> AnalyzerParameter {
111      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
112    }
113    private IFixedValueParameter<IntValue> MaximumEvaluatedSolutionsParameter {
114      get { return (IFixedValueParameter<IntValue>)Parameters["MaximumEvaluatedSolutions"]; }
115    }
116    private IFixedValueParameter<BoolValue> FillPopulationWithParentsParameter {
117      get { return (IFixedValueParameter<BoolValue>)Parameters["FillPopulationWithParents"]; }
118    }
119    private IValueParameter<MultiTerminator> TerminationParameter {
120      get { return (IValueParameter<MultiTerminator>)Parameters["Termination"]; }
121    }
122    #endregion
123
124    #region Properties
125    public IntValue Seed {
126      get { return SeedParameter.Value; }
127      set { SeedParameter.Value = value; }
128    }
129    public BoolValue SetSeedRandomly {
130      get { return SetSeedRandomlyParameter.Value; }
131      set { SetSeedRandomlyParameter.Value = value; }
132    }
133    public IntValue PopulationSize {
134      get { return PopulationSizeParameter.Value; }
135      set { PopulationSizeParameter.Value = value; }
136    }
137    public ISelector Selector {
138      get { return SelectorParameter.Value; }
139      set { SelectorParameter.Value = value; }
140    }
141    public ICrossover Crossover {
142      get { return CrossoverParameter.Value; }
143      set { CrossoverParameter.Value = value; }
144    }
145    public PercentValue MutationProbability {
146      get { return MutationProbabilityParameter.Value; }
147      set { MutationProbabilityParameter.Value = value; }
148    }
149    public IManipulator Mutator {
150      get { return MutatorParameter.Value; }
151      set { MutatorParameter.Value = value; }
152    }
153    public IntValue Elites {
154      get { return ElitesParameter.Value; }
155      set { ElitesParameter.Value = value; }
156    }
157    public bool ReevaluteElites {
158      get { return ReevaluateElitesParameter.Value.Value; }
159      set { ReevaluateElitesParameter.Value.Value = value; }
160    }
161    public int MaximumGenerations {
162      get { return MaximumGenerationsParameter.Value.Value; }
163      set { MaximumGenerationsParameter.Value.Value = value; }
164    }
165    public DoubleValue SuccessRatio {
166      get { return SuccessRatioParameter.Value; }
167      set { SuccessRatioParameter.Value = value; }
168    }
169    public DoubleValue ComparisonFactorLowerBound {
170      get { return ComparisonFactorLowerBoundParameter.Value; }
171      set { ComparisonFactorLowerBoundParameter.Value = value; }
172    }
173    public DoubleValue ComparisonFactorUpperBound {
174      get { return ComparisonFactorUpperBoundParameter.Value; }
175      set { ComparisonFactorUpperBoundParameter.Value = value; }
176    }
177    public IDiscreteDoubleValueModifier ComparisonFactorModifier {
178      get { return ComparisonFactorModifierParameter.Value; }
179      set { ComparisonFactorModifierParameter.Value = value; }
180    }
181    public DoubleValue MaximumSelectionPressure {
182      get { return MaximumSelectionPressureParameter.Value; }
183      set { MaximumSelectionPressureParameter.Value = value; }
184    }
185    public BoolValue OffspringSelectionBeforeMutation {
186      get { return OffspringSelectionBeforeMutationParameter.Value; }
187      set { OffspringSelectionBeforeMutationParameter.Value = value; }
188    }
189    public IntValue SelectedParents {
190      get { return SelectedParentsParameter.Value; }
191      set { SelectedParentsParameter.Value = value; }
192    }
193    public MultiAnalyzer Analyzer {
194      get { return AnalyzerParameter.Value; }
195      set { AnalyzerParameter.Value = value; }
196    }
197    public int MaximumEvaluatedSolutions {
198      get { return MaximumEvaluatedSolutionsParameter.Value.Value; }
199      set { MaximumEvaluatedSolutionsParameter.Value.Value = value; }
200    }
201    public bool FillPopulationWithParents {
202      get { return FillPopulationWithParentsParameter.Value.Value; }
203      set { FillPopulationWithParentsParameter.Value.Value = value; }
204    }
205    private MultiTerminator Terminators {
206      get { return TerminationParameter.Value; }
207    }
208    private RandomCreator RandomCreator {
209      get { return (RandomCreator)OperatorGraph.InitialOperator; }
210    }
211    private SolutionsCreator SolutionsCreator {
212      get { return (SolutionsCreator)RandomCreator.Successor; }
213    }
214    private OffspringSelectionGeneticAlgorithmMainLoop MainLoop {
215      get { return FindMainLoop(SolutionsCreator.Successor); }
216    }
217    [Storable]
218    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
219    [Storable]
220    private ValueAnalyzer selectionPressureAnalyzer;
221    [Storable]
222    private SuccessfulOffspringAnalyzer successfulOffspringAnalyzer;
223    [Storable]
224    private ComparisonTerminator<IntValue> generationsTerminator;
225    [Storable]
226    private ComparisonTerminator<IntValue> evaluationsTerminator;
227    [Storable]
228    private ComparisonTerminator<DoubleValue> selectionPressureTerminator;
229    [Storable]
230    private SingleObjectiveQualityTerminator qualityTerminator;
231    [Storable]
232    private ExecutionTimeTerminator executionTimeTerminator;
233    #endregion
234
235    [StorableConstructor]
236    private OffspringSelectionGeneticAlgorithm(bool deserializing) : base(deserializing) { }
237    [StorableHook(HookType.AfterDeserialization)]
238    private void AfterDeserialization() {
239      // BackwardsCompatibility3.3
240      #region Backwards compatible code, remove with 3.4
241      if (successfulOffspringAnalyzer == null)
242        successfulOffspringAnalyzer = new SuccessfulOffspringAnalyzer();
243      if (!Parameters.ContainsKey("ReevaluateElites")) {
244        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 });
245      }
246      if (!Parameters.ContainsKey("FillPopulationWithParents"))
247        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 });
248      #endregion
249
250      Initialize();
251    }
252    private OffspringSelectionGeneticAlgorithm(OffspringSelectionGeneticAlgorithm original, Cloner cloner)
253      : base(original, cloner) {
254      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
255      selectionPressureAnalyzer = cloner.Clone(original.selectionPressureAnalyzer);
256      successfulOffspringAnalyzer = cloner.Clone(original.successfulOffspringAnalyzer);
257      generationsTerminator = cloner.Clone(original.generationsTerminator);
258      evaluationsTerminator = cloner.Clone(original.evaluationsTerminator);
259      selectionPressureTerminator = cloner.Clone(original.selectionPressureTerminator);
260      qualityTerminator = cloner.Clone(original.qualityTerminator);
261      executionTimeTerminator = cloner.Clone(original.executionTimeTerminator);
262      Initialize();
263    }
264    public override IDeepCloneable Clone(Cloner cloner) {
265      return new OffspringSelectionGeneticAlgorithm(this, cloner);
266    }
267    public OffspringSelectionGeneticAlgorithm()
268      : base() {
269      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
270      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
271      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions.", new IntValue(100)));
272      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
273      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
274      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
275      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
276      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
277      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 });
278      Parameters.Add(new FixedValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations which should be processed.", new IntValue(1000)));
279      Parameters.Add(new ValueLookupParameter<DoubleValue>("SuccessRatio", "The ratio of successful to total children that should be achieved.", new DoubleValue(1)));
280      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactorLowerBound", "The lower bound of the comparison factor (start).", new DoubleValue(0)));
281      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactorUpperBound", "The upper bound of the comparison factor (end).", new DoubleValue(1)));
282      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("ComparisonFactorModifier", "The operator used to modify the comparison factor.", new ItemSet<IDiscreteDoubleValueModifier>(new IDiscreteDoubleValueModifier[] { new LinearDiscreteDoubleValueModifier() }), new LinearDiscreteDoubleValueModifier()));
283      Parameters.Add(new ValueLookupParameter<DoubleValue>("MaximumSelectionPressure", "The maximum selection pressure that terminates the algorithm.", new DoubleValue(100)));
284      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)));
285      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)));
286      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
287      Parameters.Add(new FixedValueParameter<IntValue>("MaximumEvaluatedSolutions", "The maximum number of evaluated solutions (approximately).", new IntValue(int.MaxValue)));
288      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 });
289      Parameters.Add(new ValueParameter<MultiTerminator>("Termination", "The termination criteria which sould be checked.", new MultiTerminator()));
290
291      RandomCreator randomCreator = new RandomCreator();
292      SolutionsCreator solutionsCreator = new SolutionsCreator();
293      SubScopesCounter subScopesCounter = new SubScopesCounter();
294      ResultsCollector resultsCollector = new ResultsCollector();
295      OffspringSelectionGeneticAlgorithmMainLoop mainLoop = new OffspringSelectionGeneticAlgorithmMainLoop();
296      OperatorGraph.InitialOperator = randomCreator;
297
298      randomCreator.RandomParameter.ActualName = "Random";
299      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
300      randomCreator.SeedParameter.Value = null;
301      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
302      randomCreator.SetSeedRandomlyParameter.Value = null;
303      randomCreator.Successor = solutionsCreator;
304
305      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
306      solutionsCreator.Successor = subScopesCounter;
307
308      subScopesCounter.Name = "Initialize EvaluatedSolutions";
309      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
310      subScopesCounter.Successor = resultsCollector;
311
312      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", "", "EvaluatedSolutions"));
313      resultsCollector.ResultsParameter.ActualName = "Results";
314      resultsCollector.Successor = mainLoop;
315
316      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
317      mainLoop.ComparisonFactorModifierParameter.ActualName = ComparisonFactorModifierParameter.Name;
318      mainLoop.ComparisonFactorParameter.ActualName = "ComparisonFactor";
319      mainLoop.ComparisonFactorStartParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
320      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
321      mainLoop.ElitesParameter.ActualName = ElitesParameter.Name;
322      mainLoop.ReevaluateElitesParameter.ActualName = ReevaluateElitesParameter.Name;
323      mainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
324      mainLoop.MaximumGenerationsParameter.ActualName = MaximumGenerationsParameter.Name;
325      mainLoop.MaximumSelectionPressureParameter.ActualName = MaximumSelectionPressureParameter.Name;
326      mainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
327      mainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
328      mainLoop.OffspringSelectionBeforeMutationParameter.ActualName = OffspringSelectionBeforeMutationParameter.Name;
329      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
330      mainLoop.ResultsParameter.ActualName = "Results";
331      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
332      mainLoop.SuccessRatioParameter.ActualName = SuccessRatioParameter.Name;
333      mainLoop.FillPopulationWithParentsParameter.ActualName = FillPopulationWithParentsParameter.Name;
334
335      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is IMultiObjectiveSelector)).OrderBy(x => x.Name))
336        SelectorParameter.ValidValues.Add(selector);
337      ISelector proportionalSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("ProportionalSelector"));
338      if (proportionalSelector != null) SelectorParameter.Value = proportionalSelector;
339      ParameterizeSelectors();
340
341      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
342      selectionPressureAnalyzer = new ValueAnalyzer();
343      successfulOffspringAnalyzer = new SuccessfulOffspringAnalyzer();
344      ParameterizeAnalyzers();
345      UpdateAnalyzers();
346
347      foreach (IDiscreteDoubleValueModifier modifier in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name))
348        ComparisonFactorModifierParameter.ValidValues.Add(modifier);
349      IDiscreteDoubleValueModifier linearModifier = ComparisonFactorModifierParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("LinearDiscreteDoubleValueModifier"));
350      if (linearModifier != null) ComparisonFactorModifierParameter.Value = linearModifier;
351      ParameterizeComparisonFactorModifiers();
352
353      generationsTerminator = new ComparisonTerminator<IntValue>("Generations", ComparisonType.Less, MaximumGenerationsParameter) { Name = "Generations" };
354      evaluationsTerminator = new ComparisonTerminator<IntValue>("EvaluatedSolutions", ComparisonType.Less, MaximumEvaluatedSolutionsParameter) { Name = "Evaluations" };
355      selectionPressureTerminator = new ComparisonTerminator<DoubleValue>("SelectionPressure", ComparisonType.Less, MaximumSelectionPressure) { Name = "Selection Pressure" };
356      qualityTerminator = new SingleObjectiveQualityTerminator() { Name = "Quality" };
357      executionTimeTerminator = new ExecutionTimeTerminator(this, new TimeSpanValue(TimeSpan.FromMinutes(5)));
358      ParameterizeTerminators();
359      UpdateTerminators();
360
361      Initialize();
362    }
363
364
365
366    public override void Prepare() {
367      if (Problem != null) base.Prepare();
368    }
369
370    #region Events
371    protected override void OnProblemChanged() {
372      ParameterizeStochasticOperator(Problem.SolutionCreator);
373      ParameterizeStochasticOperator(Problem.Evaluator);
374      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
375      ParameterizeSolutionsCreator();
376      ParameterizMainLoop();
377      ParameterizeSelectors();
378      ParameterizeAnalyzers();
379      ParameterizeTerminators();
380      ParameterizeIterationBasedOperators();
381      UpdateCrossovers();
382      UpdateMutators();
383      UpdateAnalyzers();
384      UpdateTerminators();
385      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
386      base.OnProblemChanged();
387    }
388
389    protected override void RegisterProblemEvents() {
390      base.RegisterProblemEvents();
391      var maximizationParameter = (IValueParameter<BoolValue>)Problem.MaximizationParameter;
392      if (maximizationParameter != null) maximizationParameter.ValueChanged += new EventHandler(MaximizationParameter_ValueChanged);
393    }
394    protected override void DeregisterProblemEvents() {
395      var maximizationParameter = (IValueParameter<BoolValue>)Problem.MaximizationParameter;
396      if (maximizationParameter != null) maximizationParameter.ValueChanged -= new EventHandler(MaximizationParameter_ValueChanged);
397      base.DeregisterProblemEvents();
398    }
399
400    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
401      ParameterizeStochasticOperator(Problem.SolutionCreator);
402      ParameterizeSolutionsCreator();
403      base.Problem_SolutionCreatorChanged(sender, e);
404    }
405    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
406      ParameterizeStochasticOperator(Problem.Evaluator);
407      ParameterizeSolutionsCreator();
408      ParameterizMainLoop();
409      ParameterizeSelectors();
410      ParameterizeAnalyzers();
411      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
412      base.Problem_EvaluatorChanged(sender, e);
413    }
414    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
415      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
416      ParameterizeIterationBasedOperators();
417      UpdateCrossovers();
418      UpdateMutators();
419      UpdateAnalyzers();
420      UpdateTerminators();
421      base.Problem_OperatorsChanged(sender, e);
422    }
423    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
424      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
425      ParameterizeSelectors();
426    }
427    private void Elites_ValueChanged(object sender, EventArgs e) {
428      ParameterizeSelectors();
429    }
430    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
431      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
432      ParameterizeSelectors();
433    }
434    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
435      ParameterizeSelectors();
436    }
437    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
438      ParameterizMainLoop();
439      ParameterizeSelectors();
440      ParameterizeAnalyzers();
441    }
442    private void MaximizationParameter_ValueChanged(object sender, EventArgs e) {
443      ParameterizeTerminators();
444    }
445    private void QualityAnalyzer_CurrentBestQualityParameter_NameChanged(object sender, EventArgs e) {
446      ParameterizeTerminators();
447    }
448    #endregion
449
450    #region Helpers
451    private void Initialize() {
452      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
453      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
454      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
455      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
456      qualityAnalyzer.CurrentBestQualityParameter.NameChanged += new EventHandler(QualityAnalyzer_CurrentBestQualityParameter_NameChanged);
457      if (Problem != null) {
458        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
459      }
460    }
461    private void ParameterizeSolutionsCreator() {
462      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
463      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
464    }
465    private void ParameterizMainLoop() {
466      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
467      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
468      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
469    }
470    private void ParameterizeStochasticOperator(IOperator op) {
471      if (op is IStochasticOperator)
472        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
473    }
474    private void ParameterizeSelectors() {
475      foreach (ISelector selector in SelectorParameter.ValidValues) {
476        selector.CopySelected = new BoolValue(true);
477        selector.NumberOfSelectedSubScopesParameter.Value = null;
478        selector.NumberOfSelectedSubScopesParameter.ActualName = SelectedParentsParameter.Name;
479        ParameterizeStochasticOperator(selector);
480      }
481      if (Problem != null) {
482        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
483          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
484          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
485        }
486      }
487    }
488    private void ParameterizeAnalyzers() {
489      qualityAnalyzer.ResultsParameter.ActualName = "Results";
490      selectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
491      selectionPressureAnalyzer.ResultsParameter.ActualName = "Results";
492      selectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
493      selectionPressureAnalyzer.ValueParameter.Depth = 0;
494      selectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
495      successfulOffspringAnalyzer.ResultsParameter.ActualName = "Results";
496      successfulOffspringAnalyzer.GenerationsParameter.ActualName = "Generations";
497      successfulOffspringAnalyzer.SuccessfulOffspringFlagParameter.Value.Value = "SuccessfulOffspring";
498      successfulOffspringAnalyzer.DepthParameter.Value = new IntValue(1);
499      if (Problem != null) {
500        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
501        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
502        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
503      }
504    }
505    private void ParameterizeTerminators() {
506      qualityTerminator.Parameterize(qualityAnalyzer.CurrentBestQualityParameter, Problem);
507    }
508    private void ParameterizeComparisonFactorModifiers() {
509      foreach (IDiscreteDoubleValueModifier modifier in ComparisonFactorModifierParameter.ValidValues) {
510        modifier.IndexParameter.ActualName = "Generations";
511        modifier.EndIndexParameter.ActualName = MaximumGenerationsParameter.Name;
512        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
513        modifier.StartIndexParameter.Value = new IntValue(0);
514        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
515        modifier.ValueParameter.ActualName = "ComparisonFactor";
516      }
517    }
518    private void ParameterizeIterationBasedOperators() {
519      if (Problem != null) {
520        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
521          op.IterationsParameter.ActualName = "Generations";
522          op.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name;
523        }
524      }
525    }
526    private void UpdateCrossovers() {
527      ICrossover oldCrossover = CrossoverParameter.Value;
528      CrossoverParameter.ValidValues.Clear();
529      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
530
531      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
532        CrossoverParameter.ValidValues.Add(crossover);
533
534      if (oldCrossover != null) {
535        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
536        if (crossover != null) CrossoverParameter.Value = crossover;
537        else oldCrossover = null;
538      }
539      if (oldCrossover == null && defaultCrossover != null)
540        CrossoverParameter.Value = defaultCrossover;
541    }
542    private void UpdateMutators() {
543      IManipulator oldMutator = MutatorParameter.Value;
544      MutatorParameter.ValidValues.Clear();
545      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
546        MutatorParameter.ValidValues.Add(mutator);
547      if (oldMutator != null) {
548        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
549        if (mutator != null) MutatorParameter.Value = mutator;
550      }
551    }
552    private void UpdateAnalyzers() {
553      Analyzer.Operators.Clear();
554      if (Problem != null) {
555        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
556          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
557            param.Depth = 1;
558          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
559        }
560      }
561      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
562      Analyzer.Operators.Add(selectionPressureAnalyzer, selectionPressureAnalyzer.EnabledByDefault);
563      Analyzer.Operators.Add(successfulOffspringAnalyzer, successfulOffspringAnalyzer.EnabledByDefault);
564    }
565    private void UpdateTerminators() {
566      var newTerminators = new Dictionary<ITerminator, bool> {
567        {generationsTerminator, !Terminators.Operators.Contains(generationsTerminator) || Terminators.Operators.ItemChecked(generationsTerminator)},
568        {selectionPressureTerminator, !Terminators.Operators.Contains(selectionPressureTerminator) || Terminators.Operators.ItemChecked(selectionPressureTerminator) },
569        {evaluationsTerminator, Terminators.Operators.Contains(evaluationsTerminator) && Terminators.Operators.ItemChecked(evaluationsTerminator)},
570        {qualityTerminator, Terminators.Operators.Contains(qualityTerminator) && Terminators.Operators.ItemChecked(qualityTerminator) },
571        {executionTimeTerminator, Terminators.Operators.Contains(executionTimeTerminator) && Terminators.Operators.ItemChecked(executionTimeTerminator)}
572      };
573      if (Problem != null) {
574        foreach (var terminator in Problem.Operators.OfType<ITerminator>())
575          newTerminators.Add(terminator, !Terminators.Operators.Contains(terminator) || Terminators.Operators.ItemChecked(terminator));
576      }
577
578      Terminators.Operators.Clear();
579      foreach (var newTerminator in newTerminators)
580        Terminators.Operators.Add(newTerminator.Key, newTerminator.Value);
581    }
582    private OffspringSelectionGeneticAlgorithmMainLoop FindMainLoop(IOperator start) {
583      IOperator mainLoop = start;
584      while (mainLoop != null && !(mainLoop is OffspringSelectionGeneticAlgorithmMainLoop))
585        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
586      if (mainLoop == null) return null;
587      else return (OffspringSelectionGeneticAlgorithmMainLoop)mainLoop;
588    }
589    #endregion
590  }
591}
Note: See TracBrowser for help on using the repository browser.