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

Last change on this file since 12403 was 12403, checked in by pfleck, 7 years ago

#2027 Wired Maximization-Parameter for the Quality Terminator.

File size: 32.5 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<MultiTerminator> TerminatorsParameter {
119      get { return (IValueParameter<MultiTerminator>)Parameters["Terminators"]; }
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 MultiTerminator Terminators {
206      get { return TerminatorsParameter.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> evaluatedSolutionsTerminator;
227    [Storable]
228    private ComparisonTerminator<DoubleValue> selectionPressureTerminator;
229    [Storable]
230    private ComparisonTerminator<DoubleValue> 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      evaluatedSolutionsTerminator = cloner.Clone(original.evaluatedSolutionsTerminator);
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 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<MultiTerminator>("Terminators", "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      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      generationsTerminator = new ComparisonTerminator<IntValue>("Generations", new IntValue(50), ComparisonType.GreaterOrEqual) { Name = "Generations" };
354      evaluatedSolutionsTerminator = new ComparisonTerminator<IntValue>("EvaluatedSolutions", "MaximumEvaluatedSolutions", ComparisonType.GreaterOrEqual) { Name = "Evaluations" };
355      selectionPressureTerminator = new ComparisonTerminator<DoubleValue>("SelectionPressure", "MaximumSelectionPressure", ComparisonType.GreaterOrEqual) { Name = "Selection Pressure" };
356      qualityTerminator = new ComparisonTerminator<DoubleValue>() { Name = "Quality" };
357      executionTimeTerminator = new ExecutionTimeTerminator(this, TimeSpan.FromMinutes(5)) { Name = "Execution Time" };
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      if (Problem != null) {
507        var maximizationParameter = (IValueParameter<BoolValue>)Problem.MaximizationParameter;
508        if (maximizationParameter != null) {
509          bool maximization = maximizationParameter.Value.Value;
510          qualityTerminator.Comparison = new Comparison(maximization ? ComparisonType.GreaterOrEqual : ComparisonType.LessOrEqual);
511          qualityTerminator.ThresholdParameter.Value = new DoubleValue(maximization ? double.MaxValue : double.MinValue);
512        }
513      }
514      qualityTerminator.ValueParameter.ActualName = qualityAnalyzer.CurrentBestQualityParameter.Name;
515    }
516    private void ParameterizeComparisonFactorModifiers() {
517      foreach (IDiscreteDoubleValueModifier modifier in ComparisonFactorModifierParameter.ValidValues) {
518        modifier.IndexParameter.ActualName = "Generations";
519        modifier.EndIndexParameter.ActualName = MaximumGenerationsParameter.Name;
520        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
521        modifier.StartIndexParameter.Value = new IntValue(0);
522        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
523        modifier.ValueParameter.ActualName = "ComparisonFactor";
524      }
525    }
526    private void ParameterizeIterationBasedOperators() {
527      if (Problem != null) {
528        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
529          op.IterationsParameter.ActualName = "Generations";
530          op.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name;
531        }
532      }
533    }
534    private void UpdateCrossovers() {
535      ICrossover oldCrossover = CrossoverParameter.Value;
536      CrossoverParameter.ValidValues.Clear();
537      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
538
539      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
540        CrossoverParameter.ValidValues.Add(crossover);
541
542      if (oldCrossover != null) {
543        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
544        if (crossover != null) CrossoverParameter.Value = crossover;
545        else oldCrossover = null;
546      }
547      if (oldCrossover == null && defaultCrossover != null)
548        CrossoverParameter.Value = defaultCrossover;
549    }
550    private void UpdateMutators() {
551      IManipulator oldMutator = MutatorParameter.Value;
552      MutatorParameter.ValidValues.Clear();
553      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
554        MutatorParameter.ValidValues.Add(mutator);
555      if (oldMutator != null) {
556        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
557        if (mutator != null) MutatorParameter.Value = mutator;
558      }
559    }
560    private void UpdateAnalyzers() {
561      Analyzer.Operators.Clear();
562      if (Problem != null) {
563        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
564          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
565            param.Depth = 1;
566          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
567        }
568      }
569      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
570      Analyzer.Operators.Add(selectionPressureAnalyzer, selectionPressureAnalyzer.EnabledByDefault);
571      Analyzer.Operators.Add(successfulOffspringAnalyzer, successfulOffspringAnalyzer.EnabledByDefault);
572    }
573    private void UpdateTerminators() {
574      Terminators.Operators.Clear();
575      if (Problem != null) {
576        foreach (var terminator in Problem.Operators.OfType<ITerminator>())
577          Terminators.Operators.Add(terminator);
578      }
579      Terminators.Operators.Add(generationsTerminator);
580      Terminators.Operators.Add(evaluatedSolutionsTerminator);
581      Terminators.Operators.Add(selectionPressureTerminator);
582      Terminators.Operators.Add(qualityTerminator, checkedState: false);
583      Terminators.Operators.Add(executionTimeTerminator, checkedState: false);
584    }
585    private OffspringSelectionGeneticAlgorithmMainLoop FindMainLoop(IOperator start) {
586      IOperator mainLoop = start;
587      while (mainLoop != null && !(mainLoop is OffspringSelectionGeneticAlgorithmMainLoop))
588        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
589      if (mainLoop == null) return null;
590      else return (OffspringSelectionGeneticAlgorithmMainLoop)mainLoop;
591    }
592    #endregion
593  }
594}
Note: See TracBrowser for help on using the repository browser.