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

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

#2027

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