Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm/3.3/OffspringSelectionGeneticAlgorithm.cs @ 3479

Last change on this file since 3479 was 3479, checked in by abeham, 14 years ago

added first draft of SASEGASA #839

File size: 21.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Operators;
28using HeuristicLab.Optimization;
29using HeuristicLab.Optimization.Operators;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.PluginInfrastructure;
33using HeuristicLab.Random;
34using HeuristicLab.Common;
35
36namespace HeuristicLab.Algorithms.OffspringSelectionGeneticAlgorithm {
37  /// <summary>
38  /// An offspring selection genetic algorithm.
39  /// </summary>
40  [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).")]
41  [Creatable("Algorithms")]
42  [StorableClass]
43  public sealed class OffspringSelectionGeneticAlgorithm : EngineAlgorithm {
44    #region Problem Properties
45    public override Type ProblemType {
46      get { return typeof(ISingleObjectiveProblem); }
47    }
48    public new ISingleObjectiveProblem Problem {
49      get { return (ISingleObjectiveProblem)base.Problem; }
50      set { base.Problem = value; }
51    }
52    #endregion
53
54    #region Parameter Properties
55    private ValueParameter<IntValue> SeedParameter {
56      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
57    }
58    private ValueParameter<BoolValue> SetSeedRandomlyParameter {
59      get { return (ValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
60    }
61    private ValueParameter<IntValue> PopulationSizeParameter {
62      get { return (ValueParameter<IntValue>)Parameters["PopulationSize"]; }
63    }
64    private ConstrainedValueParameter<ISelector> SelectorParameter {
65      get { return (ConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
66    }
67    private ConstrainedValueParameter<ICrossover> CrossoverParameter {
68      get { return (ConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
69    }
70    private ValueParameter<PercentValue> MutationProbabilityParameter {
71      get { return (ValueParameter<PercentValue>)Parameters["MutationProbability"]; }
72    }
73    private OptionalConstrainedValueParameter<IManipulator> MutatorParameter {
74      get { return (OptionalConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
75    }
76    private ValueParameter<IntValue> ElitesParameter {
77      get { return (ValueParameter<IntValue>)Parameters["Elites"]; }
78    }
79    private ValueParameter<IntValue> MaximumGenerationsParameter {
80      get { return (ValueParameter<IntValue>)Parameters["MaximumGenerations"]; }
81    }
82    private ValueLookupParameter<DoubleValue> SuccessRatioParameter {
83      get { return (ValueLookupParameter<DoubleValue>)Parameters["SuccessRatio"]; }
84    }
85    private ValueLookupParameter<DoubleValue> ComparisonFactorLowerBoundParameter {
86      get { return (ValueLookupParameter<DoubleValue>)Parameters["ComparisonFactorLowerBound"]; }
87    }
88    private ValueLookupParameter<DoubleValue> ComparisonFactorUpperBoundParameter {
89      get { return (ValueLookupParameter<DoubleValue>)Parameters["ComparisonFactorUpperBound"]; }
90    }
91    private OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier> ComparisonFactorModifierParameter {
92      get { return (OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>)Parameters["ComparisonFactorModifier"]; }
93    }
94    private ValueLookupParameter<DoubleValue> MaximumSelectionPressureParameter {
95      get { return (ValueLookupParameter<DoubleValue>)Parameters["MaximumSelectionPressure"]; }
96    }
97    private ValueLookupParameter<BoolValue> OffspringSelectionBeforeMutationParameter {
98      get { return (ValueLookupParameter<BoolValue>)Parameters["OffspringSelectionBeforeMutation"]; }
99    }
100    #endregion
101
102    #region Properties
103    public IntValue Seed {
104      get { return SeedParameter.Value; }
105      set { SeedParameter.Value = value; }
106    }
107    public BoolValue SetSeedRandomly {
108      get { return SetSeedRandomlyParameter.Value; }
109      set { SetSeedRandomlyParameter.Value = value; }
110    }
111    public IntValue PopulationSize {
112      get { return PopulationSizeParameter.Value; }
113      set { PopulationSizeParameter.Value = value; }
114    }
115    public ISelector Selector {
116      get { return SelectorParameter.Value; }
117      set { SelectorParameter.Value = value; }
118    }
119    public ICrossover Crossover {
120      get { return CrossoverParameter.Value; }
121      set { CrossoverParameter.Value = value; }
122    }
123    public PercentValue MutationProbability {
124      get { return MutationProbabilityParameter.Value; }
125      set { MutationProbabilityParameter.Value = value; }
126    }
127    public IManipulator Mutator {
128      get { return MutatorParameter.Value; }
129      set { MutatorParameter.Value = value; }
130    }
131    public IntValue Elites {
132      get { return ElitesParameter.Value; }
133      set { ElitesParameter.Value = value; }
134    }
135    public IntValue MaximumGenerations {
136      get { return MaximumGenerationsParameter.Value; }
137      set { MaximumGenerationsParameter.Value = value; }
138    }
139    private DoubleValue SuccessRatio {
140      get { return SuccessRatioParameter.Value; }
141      set { SuccessRatioParameter.Value = value; }
142    }
143    private DoubleValue ComparisonFactorLowerBound {
144      get { return ComparisonFactorLowerBoundParameter.Value; }
145      set { ComparisonFactorLowerBoundParameter.Value = value; }
146    }
147    private DoubleValue ComparisonFactorUpperBound {
148      get { return ComparisonFactorUpperBoundParameter.Value; }
149      set { ComparisonFactorUpperBoundParameter.Value = value; }
150    }
151    private IDiscreteDoubleValueModifier ComparisonFactorModifier {
152      get { return ComparisonFactorModifierParameter.Value; }
153      set { ComparisonFactorModifierParameter.Value = value; }
154    }
155    private DoubleValue MaximumSelectionPressure {
156      get { return MaximumSelectionPressureParameter.Value; }
157      set { MaximumSelectionPressureParameter.Value = value; }
158    }
159    private BoolValue OffspringSelectionBeforeMutation {
160      get { return OffspringSelectionBeforeMutationParameter.Value; }
161      set { OffspringSelectionBeforeMutationParameter.Value = value; }
162    }
163    private RandomCreator RandomCreator {
164      get { return (RandomCreator)OperatorGraph.InitialOperator; }
165    }
166    private SolutionsCreator SolutionsCreator {
167      get { return (SolutionsCreator)RandomCreator.Successor; }
168    }
169    private OffspringSelectionGeneticAlgorithmMainLoop MainLoop {
170      get { return (OffspringSelectionGeneticAlgorithmMainLoop)SolutionsCreator.Successor; }
171    }
172    private List<ISelector> selectors;
173    private IEnumerable<ISelector> Selectors {
174      get { return selectors; }
175    }
176    private List<IDiscreteDoubleValueModifier> comparisonFactorModifiers;
177    #endregion
178
179    [StorableConstructor]
180    private OffspringSelectionGeneticAlgorithm(bool deserializing) : base(deserializing) { }
181    public OffspringSelectionGeneticAlgorithm()
182      : base() {
183      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
184      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
185      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions.", new IntValue(100)));
186      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
187      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
188      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
189      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
190      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
191      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations which should be processed.", new IntValue(1000)));
192      Parameters.Add(new ValueLookupParameter<DoubleValue>("SuccessRatio", "The ratio of successful to total children that should be achieved.", new DoubleValue(1)));
193      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactorLowerBound", "The lower bound of the comparison factor (start).", new DoubleValue(0)));
194      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactorUpperBound", "The upper bound of the comparison factor (end).", new DoubleValue(1)));
195      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("ComparisonFactorModifier", "The operator used to modify the comparison factor.", new ItemSet<IDiscreteDoubleValueModifier>(new IDiscreteDoubleValueModifier[] { new LinearDiscreteDoubleValueModifier() }), new LinearDiscreteDoubleValueModifier()));
196      Parameters.Add(new ValueLookupParameter<DoubleValue>("MaximumSelectionPressure", "The maximum selection pressure that terminates the algorithm.", new DoubleValue(100)));
197      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)));
198
199      RandomCreator randomCreator = new RandomCreator();
200      SolutionsCreator solutionsCreator = new SolutionsCreator();
201      OffspringSelectionGeneticAlgorithmMainLoop mainLoop = new OffspringSelectionGeneticAlgorithmMainLoop();
202      OperatorGraph.InitialOperator = randomCreator;
203
204      randomCreator.RandomParameter.ActualName = "Random";
205      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
206      randomCreator.SeedParameter.Value = null;
207      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
208      randomCreator.SetSeedRandomlyParameter.Value = null;
209      randomCreator.Successor = solutionsCreator;
210
211      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
212      solutionsCreator.Successor = mainLoop;
213
214      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
215      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
216      mainLoop.ElitesParameter.ActualName = ElitesParameter.Name;
217      mainLoop.MaximumGenerationsParameter.ActualName = MaximumGenerationsParameter.Name;
218      mainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
219      mainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
220      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
221      mainLoop.ResultsParameter.ActualName = "Results";
222
223      Initialize();
224    }
225
226    public override IDeepCloneable Clone(Cloner cloner) {
227      OffspringSelectionGeneticAlgorithm clone = (OffspringSelectionGeneticAlgorithm)base.Clone(cloner);
228      clone.Initialize();
229      return clone;
230    }
231
232    public override void Prepare() {
233      if (Problem != null) base.Prepare();
234    }
235
236    #region Events
237    protected override void OnProblemChanged() {
238      ParameterizeStochasticOperator(Problem.SolutionCreator);
239      ParameterizeStochasticOperator(Problem.Evaluator);
240      ParameterizeStochasticOperator(Problem.Visualizer);
241      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
242      ParameterizeSolutionsCreator();
243      ParameterizMainLoop();
244      ParameterizeSelectors();
245      UpdateCrossovers();
246      UpdateMutators();
247      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
248      if (Problem.Visualizer != null) Problem.Visualizer.VisualizationParameter.ActualNameChanged += new EventHandler(Visualizer_VisualizationParameter_ActualNameChanged);
249      base.OnProblemChanged();
250    }
251
252    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
253      ParameterizeStochasticOperator(Problem.SolutionCreator);
254      ParameterizeSolutionsCreator();
255      base.Problem_SolutionCreatorChanged(sender, e);
256    }
257    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
258      ParameterizeStochasticOperator(Problem.Evaluator);
259      ParameterizeSolutionsCreator();
260      ParameterizMainLoop();
261      ParameterizeSelectors();
262      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
263      base.Problem_EvaluatorChanged(sender, e);
264    }
265    protected override void Problem_VisualizerChanged(object sender, EventArgs e) {
266      ParameterizeStochasticOperator(Problem.Visualizer);
267      ParameterizMainLoop();
268      if (Problem.Visualizer != null) Problem.Visualizer.VisualizationParameter.ActualNameChanged += new EventHandler(Visualizer_VisualizationParameter_ActualNameChanged);
269      base.Problem_VisualizerChanged(sender, e);
270    }
271    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
272      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
273      UpdateCrossovers();
274      UpdateMutators();
275      base.Problem_OperatorsChanged(sender, e);
276    }
277    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
278      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
279      ParameterizeSelectors();
280    }
281    private void Elites_ValueChanged(object sender, EventArgs e) {
282      ParameterizeSelectors();
283    }
284    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
285      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
286      ParameterizeSelectors();
287    }
288    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
289      ParameterizeSelectors();
290    }
291    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
292      ParameterizMainLoop();
293      ParameterizeSelectors();
294    }
295    private void Visualizer_VisualizationParameter_ActualNameChanged(object sender, EventArgs e) {
296      ParameterizMainLoop();
297    }
298    #endregion
299
300    #region Helpers
301    [StorableHook(HookType.AfterDeserialization)]
302    private void Initialize() {
303      InitializeSelectors();
304      UpdateSelectors();
305      InitializeComparisonFactorModifiers();
306      UpdateComparisonFactorModifiers();
307      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
308      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
309      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
310      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
311      if (Problem != null) {
312        UpdateCrossovers();
313        UpdateMutators();
314        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
315        if (Problem.Visualizer != null) Problem.Visualizer.VisualizationParameter.ActualNameChanged += new EventHandler(Visualizer_VisualizationParameter_ActualNameChanged);
316      }
317    }
318
319    private void ParameterizeSolutionsCreator() {
320      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
321      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
322    }
323    private void ParameterizMainLoop() {
324      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
325      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
326      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
327      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
328      MainLoop.VisualizerParameter.ActualName = Problem.VisualizerParameter.Name;
329      if (Problem.Visualizer != null)
330        MainLoop.VisualizationParameter.ActualName = Problem.Visualizer.VisualizationParameter.ActualName;
331    }
332    private void ParameterizeStochasticOperator(IOperator op) {
333      if (op is IStochasticOperator)
334        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
335    }
336    private void InitializeSelectors() {
337      selectors = new List<ISelector>();
338      selectors.AddRange(ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is IMultiObjectiveSelector)).OrderBy(x => x.Name));
339      ParameterizeSelectors();
340    }
341    private void InitializeComparisonFactorModifiers() {
342      comparisonFactorModifiers = new List<IDiscreteDoubleValueModifier>();
343      comparisonFactorModifiers.AddRange(ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name));
344      ParameterizeComparisonFactorModifiers();
345    }
346    private void ParameterizeSelectors() {
347      foreach (ISelector selector in Selectors) {
348        selector.CopySelected = new BoolValue(true);
349        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSizeParameter.Value.Value - ElitesParameter.Value.Value));
350        ParameterizeStochasticOperator(selector);
351      }
352      if (Problem != null) {
353        foreach (ISingleObjectiveSelector selector in Selectors.OfType<ISingleObjectiveSelector>()) {
354          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
355          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
356        }
357      }
358    }
359    private void ParameterizeComparisonFactorModifiers() {
360      foreach (IDiscreteDoubleValueModifier modifier in comparisonFactorModifiers) {
361        modifier.IndexParameter.ActualName = "Generations";
362        modifier.EndIndexParameter.ActualName = MaximumGenerationsParameter.Name;
363        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
364        modifier.StartIndexParameter.Value = new IntValue(0);
365        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
366        modifier.ValueParameter.ActualName = "ComparisonFactor";
367      }
368    }
369    private void UpdateSelectors() {
370      ISelector oldSelector = SelectorParameter.Value;
371      SelectorParameter.ValidValues.Clear();
372      foreach (ISelector selector in Selectors.OrderBy(x => x.Name))
373        SelectorParameter.ValidValues.Add(selector);
374
375      ISelector proportionalSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("ProportionalSelector"));
376      if (proportionalSelector != null) SelectorParameter.Value = proportionalSelector;
377
378      if (oldSelector != null) {
379        ISelector selector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldSelector.GetType());
380        if (selector != null) SelectorParameter.Value = selector;
381      }
382    }
383    private void UpdateComparisonFactorModifiers() {
384      IDiscreteDoubleValueModifier oldModifier = ComparisonFactorModifier;
385
386      ComparisonFactorModifierParameter.ValidValues.Clear();
387      foreach (IDiscreteDoubleValueModifier modifier in comparisonFactorModifiers)
388        ComparisonFactorModifierParameter.ValidValues.Add(modifier);
389
390      if (oldModifier != null) {
391        IDiscreteDoubleValueModifier mod = ComparisonFactorModifierParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldModifier.GetType());
392        if (mod != null) ComparisonFactorModifierParameter.Value = mod;
393      }
394    }
395    private void UpdateCrossovers() {
396      ICrossover oldCrossover = CrossoverParameter.Value;
397      CrossoverParameter.ValidValues.Clear();
398      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
399        CrossoverParameter.ValidValues.Add(crossover);
400      if (oldCrossover != null) {
401        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
402        if (crossover != null) CrossoverParameter.Value = crossover;
403      }
404    }
405    private void UpdateMutators() {
406      IManipulator oldMutator = MutatorParameter.Value;
407      MutatorParameter.ValidValues.Clear();
408      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
409        MutatorParameter.ValidValues.Add(mutator);
410      if (oldMutator != null) {
411        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
412        if (mutator != null) MutatorParameter.Value = mutator;
413      }
414    }
415    #endregion
416  }
417}
Note: See TracBrowser for help on using the repository browser.