Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4852 was 4722, checked in by swagner, 14 years ago

Merged cloning refactoring branch back into trunk (#922)

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