Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.GeneticAlgorithm/3.3/GeneticAlgorithm.cs @ 3580

Last change on this file since 3580 was 3376, checked in by swagner, 15 years ago

Moved interfaces and classes for deep cloning from HeuristicLab.Core to HeuristicLab.Common (#975).

File size: 16.3 KB
RevLine 
[2]1#region License Information
2/* HeuristicLab
[2851]3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[2]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
[2865]22using System;
[2986]23using System.Collections.Generic;
[2865]24using System.Linq;
[3376]25using HeuristicLab.Common;
[2]26using HeuristicLab.Core;
27using HeuristicLab.Data;
[2851]28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
[3021]30using HeuristicLab.Optimization.Operators;
[2852]31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[2882]33using HeuristicLab.PluginInfrastructure;
[3368]34using HeuristicLab.Random;
[2]35
[3196]36namespace HeuristicLab.Algorithms.GeneticAlgorithm {
[1153]37  /// <summary>
[3198]38  /// A genetic algorithm.
[1153]39  /// </summary>
[3198]40  [Item("Genetic Algorithm", "A genetic algorithm.")]
[2851]41  [Creatable("Algorithms")]
[3017]42  [StorableClass]
[3198]43  public sealed class GeneticAlgorithm : EngineAlgorithm {
[2986]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
[2852]53
[2986]54    #region Parameter Properties
[3048]55    private ValueParameter<IntValue> SeedParameter {
56      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
[2986]57    }
[3048]58    private ValueParameter<BoolValue> SetSeedRandomlyParameter {
59      get { return (ValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
[2986]60    }
[3048]61    private ValueParameter<IntValue> PopulationSizeParameter {
62      get { return (ValueParameter<IntValue>)Parameters["PopulationSize"]; }
[2986]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    }
[3095]70    private ValueParameter<PercentValue> MutationProbabilityParameter {
71      get { return (ValueParameter<PercentValue>)Parameters["MutationProbability"]; }
[2986]72    }
73    private OptionalConstrainedValueParameter<IManipulator> MutatorParameter {
74      get { return (OptionalConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
75    }
[3048]76    private ValueParameter<IntValue> ElitesParameter {
77      get { return (ValueParameter<IntValue>)Parameters["Elites"]; }
[2986]78    }
[3048]79    private ValueParameter<IntValue> MaximumGenerationsParameter {
80      get { return (ValueParameter<IntValue>)Parameters["MaximumGenerations"]; }
[2986]81    }
82    #endregion
[2865]83
[2986]84    #region Properties
[3048]85    public IntValue Seed {
[2986]86      get { return SeedParameter.Value; }
87      set { SeedParameter.Value = value; }
88    }
[3048]89    public BoolValue SetSeedRandomly {
[2986]90      get { return SetSeedRandomlyParameter.Value; }
91      set { SetSeedRandomlyParameter.Value = value; }
92    }
[3048]93    public IntValue PopulationSize {
[2986]94      get { return PopulationSizeParameter.Value; }
95      set { PopulationSizeParameter.Value = value; }
96    }
97    public ISelector Selector {
98      get { return SelectorParameter.Value; }
99      set { SelectorParameter.Value = value; }
100    }
101    public ICrossover Crossover {
102      get { return CrossoverParameter.Value; }
103      set { CrossoverParameter.Value = value; }
104    }
[3095]105    public PercentValue MutationProbability {
[2986]106      get { return MutationProbabilityParameter.Value; }
107      set { MutationProbabilityParameter.Value = value; }
108    }
109    public IManipulator Mutator {
110      get { return MutatorParameter.Value; }
111      set { MutatorParameter.Value = value; }
112    }
[3048]113    public IntValue Elites {
[2986]114      get { return ElitesParameter.Value; }
115      set { ElitesParameter.Value = value; }
116    }
[3048]117    public IntValue MaximumGenerations {
[2986]118      get { return MaximumGenerationsParameter.Value; }
119      set { MaximumGenerationsParameter.Value = value; }
120    }
121    private RandomCreator RandomCreator {
122      get { return (RandomCreator)OperatorGraph.InitialOperator; }
123    }
[3023]124    private SolutionsCreator SolutionsCreator {
125      get { return (SolutionsCreator)RandomCreator.Successor; }
[2986]126    }
[3198]127    private GeneticAlgorithmMainLoop GeneticAlgorithmMainLoop {
128      get { return (GeneticAlgorithmMainLoop)SolutionsCreator.Successor; }
[2986]129    }
130    private List<ISelector> selectors;
131    private IEnumerable<ISelector> Selectors {
132      get { return selectors; }
133    }
134    #endregion
[2852]135
[3198]136    public GeneticAlgorithm()
[2986]137      : base() {
[3048]138      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
139      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
140      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions.", new IntValue(100)));
[2986]141      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
142      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
[3095]143      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
[2986]144      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
[3048]145      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
146      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations which should be processed.", new IntValue(1000)));
[2]147
[2986]148      RandomCreator randomCreator = new RandomCreator();
[3023]149      SolutionsCreator solutionsCreator = new SolutionsCreator();
[3198]150      GeneticAlgorithmMainLoop geneticAlgorithmMainLoop = new GeneticAlgorithmMainLoop();
[2986]151      OperatorGraph.InitialOperator = randomCreator;
[2882]152
[2986]153      randomCreator.RandomParameter.ActualName = "Random";
154      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
155      randomCreator.SeedParameter.Value = null;
156      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
157      randomCreator.SetSeedRandomlyParameter.Value = null;
[3023]158      randomCreator.Successor = solutionsCreator;
[2]159
[3023]160      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
[3198]161      solutionsCreator.Successor = geneticAlgorithmMainLoop;
[2]162
[3198]163      geneticAlgorithmMainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
164      geneticAlgorithmMainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
165      geneticAlgorithmMainLoop.ElitesParameter.ActualName = ElitesParameter.Name;
166      geneticAlgorithmMainLoop.MaximumGenerationsParameter.ActualName = MaximumGenerationsParameter.Name;
167      geneticAlgorithmMainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
168      geneticAlgorithmMainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
169      geneticAlgorithmMainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
170      geneticAlgorithmMainLoop.ResultsParameter.ActualName = "Results";
[2]171
[3280]172      Initialize();
[2986]173    }
174    [StorableConstructor]
[3280]175    private GeneticAlgorithm(bool deserializing) : base(deserializing) { }
[2]176
[2986]177    public override IDeepCloneable Clone(Cloner cloner) {
[3198]178      GeneticAlgorithm clone = (GeneticAlgorithm)base.Clone(cloner);
[3280]179      clone.Initialize();
[2986]180      return clone;
181    }
[2882]182
[3275]183    public override void Prepare() {
184      if (Problem != null) base.Prepare();
[3188]185    }
186
[2986]187    #region Events
188    protected override void OnProblemChanged() {
189      ParameterizeStochasticOperator(Problem.SolutionCreator);
190      ParameterizeStochasticOperator(Problem.Evaluator);
[3107]191      ParameterizeStochasticOperator(Problem.Visualizer);
[2986]192      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
[3023]193      ParameterizeSolutionsCreator();
[3198]194      ParameterizeGeneticAlgorithmMainLoop();
[2986]195      ParameterizeSelectors();
196      UpdateCrossovers();
197      UpdateMutators();
198      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
[3139]199      if (Problem.Visualizer != null) Problem.Visualizer.VisualizationParameter.ActualNameChanged += new EventHandler(Visualizer_VisualizationParameter_ActualNameChanged);
[2986]200      base.OnProblemChanged();
201    }
[3139]202
[2986]203    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
204      ParameterizeStochasticOperator(Problem.SolutionCreator);
[3023]205      ParameterizeSolutionsCreator();
[2986]206      base.Problem_SolutionCreatorChanged(sender, e);
207    }
208    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
209      ParameterizeStochasticOperator(Problem.Evaluator);
[3023]210      ParameterizeSolutionsCreator();
[3198]211      ParameterizeGeneticAlgorithmMainLoop();
[2986]212      ParameterizeSelectors();
213      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
214      base.Problem_EvaluatorChanged(sender, e);
215    }
[3107]216    protected override void Problem_VisualizerChanged(object sender, EventArgs e) {
217      ParameterizeStochasticOperator(Problem.Visualizer);
[3198]218      ParameterizeGeneticAlgorithmMainLoop();
[3139]219      if (Problem.Visualizer != null) Problem.Visualizer.VisualizationParameter.ActualNameChanged += new EventHandler(Visualizer_VisualizationParameter_ActualNameChanged);
[3107]220      base.Problem_VisualizerChanged(sender, e);
221    }
[2986]222    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
223      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
224      UpdateCrossovers();
225      UpdateMutators();
226      base.Problem_OperatorsChanged(sender, e);
227    }
228    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
229      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
230      ParameterizeSelectors();
231    }
232    private void Elites_ValueChanged(object sender, EventArgs e) {
233      ParameterizeSelectors();
234    }
235    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
236      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
237      ParameterizeSelectors();
238    }
239    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
240      ParameterizeSelectors();
241    }
242    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
[3198]243      ParameterizeGeneticAlgorithmMainLoop();
[2986]244      ParameterizeSelectors();
245    }
[3139]246    private void Visualizer_VisualizationParameter_ActualNameChanged(object sender, EventArgs e) {
[3198]247      ParameterizeGeneticAlgorithmMainLoop();
[3139]248    }
[2986]249    #endregion
[2852]250
[2986]251    #region Helpers
252    [StorableHook(HookType.AfterDeserialization)]
[3280]253    private void Initialize() {
[2986]254      InitializeSelectors();
255      UpdateSelectors();
256      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
257      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
258      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
259      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
[3139]260      if (Problem != null) {
261        UpdateCrossovers();
262        UpdateMutators();
[2986]263        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
[3139]264        if (Problem.Visualizer != null) Problem.Visualizer.VisualizationParameter.ActualNameChanged += new EventHandler(Visualizer_VisualizationParameter_ActualNameChanged);
265      }
[2986]266    }
[2852]267
[3023]268    private void ParameterizeSolutionsCreator() {
269      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
270      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
[2986]271    }
[3198]272    private void ParameterizeGeneticAlgorithmMainLoop() {
273      GeneticAlgorithmMainLoop.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
274      GeneticAlgorithmMainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
275      GeneticAlgorithmMainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
276      GeneticAlgorithmMainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
277      GeneticAlgorithmMainLoop.VisualizerParameter.ActualName = Problem.VisualizerParameter.Name;
[3139]278      if (Problem.Visualizer != null)
[3198]279        GeneticAlgorithmMainLoop.VisualizationParameter.ActualName = Problem.Visualizer.VisualizationParameter.ActualName;
[2986]280    }
281    private void ParameterizeStochasticOperator(IOperator op) {
282      if (op is IStochasticOperator)
283        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
284    }
285    private void InitializeSelectors() {
286      selectors = new List<ISelector>();
[3303]287      selectors.AddRange(ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is IMultiObjectiveSelector)).OrderBy(x => x.Name));
[3199]288      ParameterizeSelectors();
[2986]289    }
290    private void ParameterizeSelectors() {
291      foreach (ISelector selector in Selectors) {
[3048]292        selector.CopySelected = new BoolValue(true);
293        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSizeParameter.Value.Value - ElitesParameter.Value.Value));
[2986]294        ParameterizeStochasticOperator(selector);
295      }
296      if (Problem != null) {
297        foreach (ISingleObjectiveSelector selector in Selectors.OfType<ISingleObjectiveSelector>()) {
298          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
299          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
300        }
301      }
302    }
303    private void UpdateSelectors() {
[3303]304      ISelector oldSelector = SelectorParameter.Value;
305      SelectorParameter.ValidValues.Clear();
306      foreach (ISelector selector in Selectors.OrderBy(x => x.Name))
307        SelectorParameter.ValidValues.Add(selector);
[3304]308
309      ISelector proportionalSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("ProportionalSelector"));
310      if (proportionalSelector != null) SelectorParameter.Value = proportionalSelector;
311
[3303]312      if (oldSelector != null) {
313        ISelector selector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldSelector.GetType());
314        if (selector != null) SelectorParameter.Value = selector;
[2986]315      }
316    }
317    private void UpdateCrossovers() {
[3303]318      ICrossover oldCrossover = CrossoverParameter.Value;
319      CrossoverParameter.ValidValues.Clear();
320      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
321        CrossoverParameter.ValidValues.Add(crossover);
322      if (oldCrossover != null) {
323        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
324        if (crossover != null) CrossoverParameter.Value = crossover;
[3076]325      }
[2986]326    }
327    private void UpdateMutators() {
[3303]328      IManipulator oldMutator = MutatorParameter.Value;
329      MutatorParameter.ValidValues.Clear();
330      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
331        MutatorParameter.ValidValues.Add(mutator);
332      if (oldMutator != null) {
333        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
334        if (mutator != null) MutatorParameter.Value = mutator;
[3076]335      }
[2986]336    }
337    #endregion
[2]338  }
339}
Note: See TracBrowser for help on using the repository browser.