Free cookie consent management tool by TermsFeed Policy Generator

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

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

Updated Gender Specific Selection, Offspring Selector and other changes related to the OSGA #976
Removed old OS plugin, removed SelectedSubScopesLookupParameter

File size: 21.6 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 ConstrainedValueParameter<IDiscreteDoubleValueModifier> ComparisonFactorModifierParameter {
92      get { return (ConstrainedValueParameter<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 ConstrainedValueParameter<IDiscreteDoubleValueModifier>("ComparisonFactorModifier", "The operator used to modify the comparison factor."));
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.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
215      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
216      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
217      mainLoop.ElitesParameter.ActualName = ElitesParameter.Name;
218      mainLoop.MaximumGenerationsParameter.ActualName = MaximumGenerationsParameter.Name;
219      mainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
220      mainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
221      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
222      mainLoop.ResultsParameter.ActualName = "Results";
223
224      Initialize();
225    }
226
227    public override IDeepCloneable Clone(Cloner cloner) {
228      OffspringSelectionGeneticAlgorithm clone = (OffspringSelectionGeneticAlgorithm)base.Clone(cloner);
229      clone.Initialize();
230      return clone;
231    }
232
233    public override void Prepare() {
234      if (Problem != null) base.Prepare();
235    }
236
237    #region Events
238    protected override void OnProblemChanged() {
239      ParameterizeStochasticOperator(Problem.SolutionCreator);
240      ParameterizeStochasticOperator(Problem.Evaluator);
241      ParameterizeStochasticOperator(Problem.Visualizer);
242      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
243      ParameterizeSolutionsCreator();
244      ParameterizMainLoop();
245      ParameterizeSelectors();
246      UpdateCrossovers();
247      UpdateMutators();
248      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
249      if (Problem.Visualizer != null) Problem.Visualizer.VisualizationParameter.ActualNameChanged += new EventHandler(Visualizer_VisualizationParameter_ActualNameChanged);
250      base.OnProblemChanged();
251    }
252
253    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
254      ParameterizeStochasticOperator(Problem.SolutionCreator);
255      ParameterizeSolutionsCreator();
256      base.Problem_SolutionCreatorChanged(sender, e);
257    }
258    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
259      ParameterizeStochasticOperator(Problem.Evaluator);
260      ParameterizeSolutionsCreator();
261      ParameterizMainLoop();
262      ParameterizeSelectors();
263      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
264      base.Problem_EvaluatorChanged(sender, e);
265    }
266    protected override void Problem_VisualizerChanged(object sender, EventArgs e) {
267      ParameterizeStochasticOperator(Problem.Visualizer);
268      ParameterizMainLoop();
269      if (Problem.Visualizer != null) Problem.Visualizer.VisualizationParameter.ActualNameChanged += new EventHandler(Visualizer_VisualizationParameter_ActualNameChanged);
270      base.Problem_VisualizerChanged(sender, e);
271    }
272    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
273      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
274      UpdateCrossovers();
275      UpdateMutators();
276      base.Problem_OperatorsChanged(sender, e);
277    }
278    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
279      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
280      ParameterizeSelectors();
281    }
282    private void Elites_ValueChanged(object sender, EventArgs e) {
283      ParameterizeSelectors();
284    }
285    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
286      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
287      MainLoop.PopulationSizeParameter.Value = new IntValue(PopulationSize.Value - Elites.Value);
288      ParameterizeSelectors();
289    }
290    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
291      MainLoop.PopulationSizeParameter.Value = new IntValue(PopulationSize.Value - Elites.Value);
292      ParameterizeSelectors();
293    }
294    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
295      ParameterizMainLoop();
296      ParameterizeSelectors();
297    }
298    private void Visualizer_VisualizationParameter_ActualNameChanged(object sender, EventArgs e) {
299      ParameterizMainLoop();
300    }
301    #endregion
302
303    #region Helpers
304    [StorableHook(HookType.AfterDeserialization)]
305    private void Initialize() {
306      InitializeSelectors();
307      UpdateSelectors();
308      InitializeComparisonFactorModifiers();
309      UpdateComparisonFactorModifiers();
310      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
311      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
312      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
313      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
314      if (Problem != null) {
315        UpdateCrossovers();
316        UpdateMutators();
317        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
318        if (Problem.Visualizer != null) Problem.Visualizer.VisualizationParameter.ActualNameChanged += new EventHandler(Visualizer_VisualizationParameter_ActualNameChanged);
319      }
320    }
321
322    private void ParameterizeSolutionsCreator() {
323      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
324      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
325    }
326    private void ParameterizMainLoop() {
327      MainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
328      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
329      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
330      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
331      MainLoop.VisualizerParameter.ActualName = Problem.VisualizerParameter.Name;
332      if (Problem.Visualizer != null)
333        MainLoop.VisualizationParameter.ActualName = Problem.Visualizer.VisualizationParameter.ActualName;
334    }
335    private void ParameterizeStochasticOperator(IOperator op) {
336      if (op is IStochasticOperator)
337        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
338    }
339    private void InitializeSelectors() {
340      selectors = new List<ISelector>();
341      selectors.AddRange(ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is IMultiObjectiveSelector)).OrderBy(x => x.Name));
342      ParameterizeSelectors();
343    }
344    private void InitializeComparisonFactorModifiers() {
345      comparisonFactorModifiers = new List<IDiscreteDoubleValueModifier>();
346      comparisonFactorModifiers.AddRange(ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name));
347      ParameterizeComparisonFactorModifiers();
348    }
349    private void ParameterizeSelectors() {
350      foreach (ISelector selector in Selectors) {
351        selector.CopySelected = new BoolValue(true);
352        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSizeParameter.Value.Value - ElitesParameter.Value.Value));
353        ParameterizeStochasticOperator(selector);
354      }
355      if (Problem != null) {
356        foreach (ISingleObjectiveSelector selector in Selectors.OfType<ISingleObjectiveSelector>()) {
357          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
358          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
359        }
360      }
361    }
362    private void ParameterizeComparisonFactorModifiers() {
363      foreach (IDiscreteDoubleValueModifier modifier in comparisonFactorModifiers) {
364        modifier.IndexParameter.ActualName = "Generations";
365        modifier.EndIndexParameter.ActualName = MaximumGenerationsParameter.Name;
366        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
367        modifier.StartIndexParameter.Value = new IntValue(0);
368        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
369        modifier.ValueParameter.ActualName = "ComparisonFactor";
370      }
371    }
372    private void UpdateSelectors() {
373      ISelector oldSelector = SelectorParameter.Value;
374      SelectorParameter.ValidValues.Clear();
375      foreach (ISelector selector in Selectors.OrderBy(x => x.Name))
376        SelectorParameter.ValidValues.Add(selector);
377
378      ISelector proportionalSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("ProportionalSelector"));
379      if (proportionalSelector != null) SelectorParameter.Value = proportionalSelector;
380
381      if (oldSelector != null) {
382        ISelector selector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldSelector.GetType());
383        if (selector != null) SelectorParameter.Value = selector;
384      }
385    }
386    private void UpdateComparisonFactorModifiers() {
387      IDiscreteDoubleValueModifier oldModifier = ComparisonFactorModifier;
388      if (oldModifier == null) oldModifier = new LinearDiscreteDoubleValueModifier();
389
390      ComparisonFactorModifierParameter.ValidValues.Clear();
391      foreach (IDiscreteDoubleValueModifier modifier in comparisonFactorModifiers)
392        ComparisonFactorModifierParameter.ValidValues.Add(modifier);
393     
394      IDiscreteDoubleValueModifier mod = ComparisonFactorModifierParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldModifier.GetType());
395      if (mod != null) ComparisonFactorModifierParameter.Value = mod;
396    }
397    private void UpdateCrossovers() {
398      ICrossover oldCrossover = CrossoverParameter.Value;
399      CrossoverParameter.ValidValues.Clear();
400      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
401        CrossoverParameter.ValidValues.Add(crossover);
402      if (oldCrossover != null) {
403        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
404        if (crossover != null) CrossoverParameter.Value = crossover;
405      }
406    }
407    private void UpdateMutators() {
408      IManipulator oldMutator = MutatorParameter.Value;
409      MutatorParameter.ValidValues.Clear();
410      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
411        MutatorParameter.ValidValues.Add(mutator);
412      if (oldMutator != null) {
413        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
414        if (mutator != null) MutatorParameter.Value = mutator;
415      }
416    }
417    #endregion
418  }
419}
Note: See TracBrowser for help on using the repository browser.