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

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

#2027 Split update and parameterization of TerminationCriteria similar to other operators.

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.Linq;
24using HeuristicLab.Analysis;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Optimization.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Random;
35using HeuristicLab.Termination;
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 ValueParameter<IntValue> MaximumGenerationsParameter {
86      get { return (ValueParameter<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 ValueLookupParameter<DoubleValue> MaximumSelectionPressureParameter {
101      get { return (ValueLookupParameter<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 ValueParameter<IntValue> MaximumEvaluatedSolutionsParameter {
113      get { return (ValueParameter<IntValue>)Parameters["MaximumEvaluatedSolutions"]; }
114    }
115    private IFixedValueParameter<BoolValue> FillPopulationWithParentsParameter {
116      get { return (IFixedValueParameter<BoolValue>)Parameters["FillPopulationWithParents"]; }
117    }
118    private IValueParameter<MultiTerminationCriterion> TerminationCriteriaParameter {
119      get { return (IValueParameter<MultiTerminationCriterion>)Parameters["TerminationCriteria"]; }
120    }
121    #endregion
122
123    #region Properties
124    public IntValue Seed {
125      get { return SeedParameter.Value; }
126      set { SeedParameter.Value = value; }
127    }
128    public BoolValue SetSeedRandomly {
129      get { return SetSeedRandomlyParameter.Value; }
130      set { SetSeedRandomlyParameter.Value = value; }
131    }
132    public IntValue PopulationSize {
133      get { return PopulationSizeParameter.Value; }
134      set { PopulationSizeParameter.Value = value; }
135    }
136    public ISelector Selector {
137      get { return SelectorParameter.Value; }
138      set { SelectorParameter.Value = value; }
139    }
140    public ICrossover Crossover {
141      get { return CrossoverParameter.Value; }
142      set { CrossoverParameter.Value = value; }
143    }
144    public PercentValue MutationProbability {
145      get { return MutationProbabilityParameter.Value; }
146      set { MutationProbabilityParameter.Value = value; }
147    }
148    public IManipulator Mutator {
149      get { return MutatorParameter.Value; }
150      set { MutatorParameter.Value = value; }
151    }
152    public IntValue Elites {
153      get { return ElitesParameter.Value; }
154      set { ElitesParameter.Value = value; }
155    }
156    public bool ReevaluteElites {
157      get { return ReevaluateElitesParameter.Value.Value; }
158      set { ReevaluateElitesParameter.Value.Value = value; }
159    }
160    public IntValue MaximumGenerations {
161      get { return MaximumGenerationsParameter.Value; }
162      set { MaximumGenerationsParameter.Value = value; }
163    }
164    public DoubleValue SuccessRatio {
165      get { return SuccessRatioParameter.Value; }
166      set { SuccessRatioParameter.Value = value; }
167    }
168    public DoubleValue ComparisonFactorLowerBound {
169      get { return ComparisonFactorLowerBoundParameter.Value; }
170      set { ComparisonFactorLowerBoundParameter.Value = value; }
171    }
172    public DoubleValue ComparisonFactorUpperBound {
173      get { return ComparisonFactorUpperBoundParameter.Value; }
174      set { ComparisonFactorUpperBoundParameter.Value = value; }
175    }
176    public IDiscreteDoubleValueModifier ComparisonFactorModifier {
177      get { return ComparisonFactorModifierParameter.Value; }
178      set { ComparisonFactorModifierParameter.Value = value; }
179    }
180    public DoubleValue MaximumSelectionPressure {
181      get { return MaximumSelectionPressureParameter.Value; }
182      set { MaximumSelectionPressureParameter.Value = value; }
183    }
184    public BoolValue OffspringSelectionBeforeMutation {
185      get { return OffspringSelectionBeforeMutationParameter.Value; }
186      set { OffspringSelectionBeforeMutationParameter.Value = value; }
187    }
188    public IntValue SelectedParents {
189      get { return SelectedParentsParameter.Value; }
190      set { SelectedParentsParameter.Value = value; }
191    }
192    public MultiAnalyzer Analyzer {
193      get { return AnalyzerParameter.Value; }
194      set { AnalyzerParameter.Value = value; }
195    }
196
197    public IntValue MaximumEvaluatedSolutions {
198      get { return MaximumEvaluatedSolutionsParameter.Value; }
199      set { MaximumEvaluatedSolutionsParameter.Value = value; }
200    }
201    public bool FillPopulationWithParents {
202      get { return FillPopulationWithParentsParameter.Value.Value; }
203      set { FillPopulationWithParentsParameter.Value.Value = value; }
204    }
205    private MultiTerminationCriterion TerminationCriteria {
206      get { return TerminationCriteriaParameter.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 ComparisonTerminationCriterion<IntValue> maximumGenerationsTerminationCriterion;
225    [Storable]
226    private ComparisonTerminationCriterion<IntValue> maximumEvaluatedSolutionsTerminationCriterion;
227    [Storable]
228    private ComparisonTerminationCriterion<DoubleValue> maximumSelectionPressureTerminationCriterion;
229    [Storable]
230    private ComparisonTerminationCriterion<DoubleValue> qualityTerminationCriterion;
231    [Storable]
232    private ExecutionTimeTimeTerminationCriterion executionTimeTerminationCriterion;
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      maximumGenerationsTerminationCriterion = cloner.Clone(original.maximumGenerationsTerminationCriterion);
258      maximumEvaluatedSolutionsTerminationCriterion = cloner.Clone(original.maximumEvaluatedSolutionsTerminationCriterion);
259      maximumSelectionPressureTerminationCriterion = cloner.Clone(original.maximumSelectionPressureTerminationCriterion);
260      qualityTerminationCriterion = cloner.Clone(original.qualityTerminationCriterion);
261      executionTimeTerminationCriterion = cloner.Clone(original.executionTimeTerminationCriterion);
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 ValueParameter<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 ValueParameter<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<MultiTerminationCriterion>("TerminationCriteria", "The termination criteria which sould be checked.", new MultiTerminationCriterion()));
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      foreach (IDiscreteDoubleValueModifier modifier in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name))
342        ComparisonFactorModifierParameter.ValidValues.Add(modifier);
343      IDiscreteDoubleValueModifier linearModifier = ComparisonFactorModifierParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("LinearDiscreteDoubleValueModifier"));
344      if (linearModifier != null) ComparisonFactorModifierParameter.Value = linearModifier;
345      ParameterizeComparisonFactorModifiers();
346
347      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
348      selectionPressureAnalyzer = new ValueAnalyzer();
349      successfulOffspringAnalyzer = new SuccessfulOffspringAnalyzer();
350      ParameterizeAnalyzers();
351      UpdateAnalyzers();
352
353      maximumGenerationsTerminationCriterion = new ComparisonTerminationCriterion<IntValue>("Generations", "MaximumGenerations", ComparisonType.GreaterOrEqual) { Name = "Maximum Generations" };
354      maximumEvaluatedSolutionsTerminationCriterion = new ComparisonTerminationCriterion<IntValue>("EvaluatedSolutions", "MaximumEvaluatedSolutions", ComparisonType.GreaterOrEqual) { Name = "Maximum Evaluations" };
355      maximumSelectionPressureTerminationCriterion = new ComparisonTerminationCriterion<DoubleValue>("SelectionPressure", "MaximumSelectionPressure", ComparisonType.GreaterOrEqual) { Name = "Maximum Selection Pressure" };
356      qualityTerminationCriterion = new ComparisonTerminationCriterion<DoubleValue>() { Name = "Maximum/Minimum Quality" };
357      executionTimeTerminationCriterion = new ExecutionTimeTimeTerminationCriterion(this, TimeSpan.FromMinutes(5)) { Name = "Maximum Execution Time" };
358      ParameterizeTerminationCriteria();
359      UpdateTerminationCriteria();
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      ParameterizeTerminationCriteria();
380      ParameterizeIterationBasedOperators();
381      UpdateCrossovers();
382      UpdateMutators();
383      UpdateAnalyzers();
384      UpdateTerminationCriteria();
385      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
386      base.OnProblemChanged();
387    }
388
389    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
390      ParameterizeStochasticOperator(Problem.SolutionCreator);
391      ParameterizeSolutionsCreator();
392      base.Problem_SolutionCreatorChanged(sender, e);
393    }
394    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
395      ParameterizeStochasticOperator(Problem.Evaluator);
396      ParameterizeSolutionsCreator();
397      ParameterizMainLoop();
398      ParameterizeSelectors();
399      ParameterizeAnalyzers();
400      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
401      base.Problem_EvaluatorChanged(sender, e);
402    }
403    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
404      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
405      ParameterizeIterationBasedOperators();
406      UpdateCrossovers();
407      UpdateMutators();
408      UpdateAnalyzers();
409      UpdateTerminationCriteria();
410      base.Problem_OperatorsChanged(sender, e);
411    }
412    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
413      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
414      ParameterizeSelectors();
415    }
416    private void Elites_ValueChanged(object sender, EventArgs e) {
417      ParameterizeSelectors();
418    }
419    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
420      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
421      ParameterizeSelectors();
422    }
423    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
424      ParameterizeSelectors();
425    }
426    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
427      ParameterizMainLoop();
428      ParameterizeSelectors();
429      ParameterizeAnalyzers();
430    }
431    #endregion
432
433    #region Helpers
434    private void Initialize() {
435      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
436      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
437      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
438      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
439      if (Problem != null) {
440        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
441      }
442    }
443    private void ParameterizeSolutionsCreator() {
444      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
445      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
446    }
447    private void ParameterizMainLoop() {
448      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
449      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
450      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
451    }
452    private void ParameterizeStochasticOperator(IOperator op) {
453      if (op is IStochasticOperator)
454        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
455    }
456    private void ParameterizeSelectors() {
457      foreach (ISelector selector in SelectorParameter.ValidValues) {
458        selector.CopySelected = new BoolValue(true);
459        selector.NumberOfSelectedSubScopesParameter.Value = null;
460        selector.NumberOfSelectedSubScopesParameter.ActualName = SelectedParentsParameter.Name;
461        ParameterizeStochasticOperator(selector);
462      }
463      if (Problem != null) {
464        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
465          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
466          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
467        }
468      }
469    }
470    private void ParameterizeAnalyzers() {
471      qualityAnalyzer.ResultsParameter.ActualName = "Results";
472      selectionPressureAnalyzer.Name = "SelectionPressure Analyzer";
473      selectionPressureAnalyzer.ResultsParameter.ActualName = "Results";
474      selectionPressureAnalyzer.ValueParameter.ActualName = "SelectionPressure";
475      selectionPressureAnalyzer.ValueParameter.Depth = 0;
476      selectionPressureAnalyzer.ValuesParameter.ActualName = "Selection Pressure History";
477      successfulOffspringAnalyzer.ResultsParameter.ActualName = "Results";
478      successfulOffspringAnalyzer.GenerationsParameter.ActualName = "Generations";
479      successfulOffspringAnalyzer.SuccessfulOffspringFlagParameter.Value.Value = "SuccessfulOffspring";
480      successfulOffspringAnalyzer.DepthParameter.Value = new IntValue(1);
481      if (Problem != null) {
482        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
483        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
484        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
485      }
486    }
487    private void ParameterizeTerminationCriteria() {
488      if (Problem != null) {
489        bool maximization = ((BoolValue)Problem.MaximizationParameter.ActualValue).Value;
490        qualityTerminationCriterion.Name = maximization ? "Maximum Quality" : "Minimum Quality";
491        qualityTerminationCriterion.Comparison = new Comparison(maximization ? ComparisonType.GreaterOrEqual : ComparisonType.LessOrEqual);
492        qualityTerminationCriterion.LeftSideParameter.ActualName = qualityAnalyzer.CurrentBestQualityParameter.Name;
493        qualityTerminationCriterion.RightSideParameter.Value = new DoubleValue(maximization ? double.MaxValue : double.MinValue);
494      }
495    }
496    private void ParameterizeComparisonFactorModifiers() {
497      foreach (IDiscreteDoubleValueModifier modifier in ComparisonFactorModifierParameter.ValidValues) {
498        modifier.IndexParameter.ActualName = "Generations";
499        modifier.EndIndexParameter.ActualName = MaximumGenerationsParameter.Name;
500        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
501        modifier.StartIndexParameter.Value = new IntValue(0);
502        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
503        modifier.ValueParameter.ActualName = "ComparisonFactor";
504      }
505    }
506    private void ParameterizeIterationBasedOperators() {
507      if (Problem != null) {
508        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
509          op.IterationsParameter.ActualName = "Generations";
510          op.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name;
511        }
512      }
513    }
514    private void UpdateCrossovers() {
515      ICrossover oldCrossover = CrossoverParameter.Value;
516      CrossoverParameter.ValidValues.Clear();
517      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
518
519      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
520        CrossoverParameter.ValidValues.Add(crossover);
521
522      if (oldCrossover != null) {
523        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
524        if (crossover != null) CrossoverParameter.Value = crossover;
525        else oldCrossover = null;
526      }
527      if (oldCrossover == null && defaultCrossover != null)
528        CrossoverParameter.Value = defaultCrossover;
529    }
530    private void UpdateMutators() {
531      IManipulator oldMutator = MutatorParameter.Value;
532      MutatorParameter.ValidValues.Clear();
533      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
534        MutatorParameter.ValidValues.Add(mutator);
535      if (oldMutator != null) {
536        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
537        if (mutator != null) MutatorParameter.Value = mutator;
538      }
539    }
540    private void UpdateAnalyzers() {
541      Analyzer.Operators.Clear();
542      if (Problem != null) {
543        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
544          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
545            param.Depth = 1;
546          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
547        }
548      }
549      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
550      Analyzer.Operators.Add(selectionPressureAnalyzer, selectionPressureAnalyzer.EnabledByDefault);
551      Analyzer.Operators.Add(successfulOffspringAnalyzer, successfulOffspringAnalyzer.EnabledByDefault);
552    }
553    private void UpdateTerminationCriteria() {
554      TerminationCriteria.Operators.Clear();
555      if (Problem != null) {
556        foreach (var terminationCriterion in Problem.Operators.OfType<ITerminationCriterion>())
557          TerminationCriteria.Operators.Add(terminationCriterion);
558      }
559      TerminationCriteria.Operators.Add(maximumGenerationsTerminationCriterion);
560      TerminationCriteria.Operators.Add(maximumEvaluatedSolutionsTerminationCriterion);
561      TerminationCriteria.Operators.Add(maximumSelectionPressureTerminationCriterion);
562      TerminationCriteria.Operators.Add(qualityTerminationCriterion, checkedState: false);
563      TerminationCriteria.Operators.Add(executionTimeTerminationCriterion, checkedState: false);
564    }
565    private OffspringSelectionGeneticAlgorithmMainLoop FindMainLoop(IOperator start) {
566      IOperator mainLoop = start;
567      while (mainLoop != null && !(mainLoop is OffspringSelectionGeneticAlgorithmMainLoop))
568        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
569      if (mainLoop == null) return null;
570      else return (OffspringSelectionGeneticAlgorithmMainLoop)mainLoop;
571    }
572    #endregion
573  }
574}
Note: See TracBrowser for help on using the repository browser.