Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4681 was 4477, checked in by gkronber, 14 years ago

Merged r4458, r4459,r4462,r4464 from data analysis exploration branch into trunk. #1142

File size: 16.6 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) { }
[2]194
[2986]195    public override IDeepCloneable Clone(Cloner cloner) {
[3198]196      GeneticAlgorithm clone = (GeneticAlgorithm)base.Clone(cloner);
[3680]197      clone.qualityAnalyzer = (BestAverageWorstQualityAnalyzer)cloner.Clone(qualityAnalyzer);
[3280]198      clone.Initialize();
[2986]199      return clone;
200    }
[2882]201
[3275]202    public override void Prepare() {
203      if (Problem != null) base.Prepare();
[3188]204    }
205
[2986]206    #region Events
207    protected override void OnProblemChanged() {
208      ParameterizeStochasticOperator(Problem.SolutionCreator);
209      ParameterizeStochasticOperator(Problem.Evaluator);
210      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
[3023]211      ParameterizeSolutionsCreator();
[3198]212      ParameterizeGeneticAlgorithmMainLoop();
[2986]213      ParameterizeSelectors();
[3616]214      ParameterizeAnalyzers();
[3750]215      ParameterizeIterationBasedOperators();
[2986]216      UpdateCrossovers();
217      UpdateMutators();
[3616]218      UpdateAnalyzers();
[2986]219      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
220      base.OnProblemChanged();
221    }
[3139]222
[2986]223    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
224      ParameterizeStochasticOperator(Problem.SolutionCreator);
[3023]225      ParameterizeSolutionsCreator();
[2986]226      base.Problem_SolutionCreatorChanged(sender, e);
227    }
228    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
229      ParameterizeStochasticOperator(Problem.Evaluator);
[3023]230      ParameterizeSolutionsCreator();
[3198]231      ParameterizeGeneticAlgorithmMainLoop();
[2986]232      ParameterizeSelectors();
[3616]233      ParameterizeAnalyzers();
[2986]234      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
235      base.Problem_EvaluatorChanged(sender, e);
236    }
237    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
238      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
[3750]239      ParameterizeIterationBasedOperators();
[2986]240      UpdateCrossovers();
241      UpdateMutators();
[3616]242      UpdateAnalyzers();
[2986]243      base.Problem_OperatorsChanged(sender, e);
244    }
245    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
246      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
247      ParameterizeSelectors();
248    }
249    private void Elites_ValueChanged(object sender, EventArgs e) {
250      ParameterizeSelectors();
251    }
252    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
253      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
254      ParameterizeSelectors();
255    }
256    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
257      ParameterizeSelectors();
258    }
259    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
[3198]260      ParameterizeGeneticAlgorithmMainLoop();
[2986]261      ParameterizeSelectors();
[3616]262      ParameterizeAnalyzers();
[2986]263    }
264    #endregion
[2852]265
[2986]266    #region Helpers
267    [StorableHook(HookType.AfterDeserialization)]
[3280]268    private void Initialize() {
[2986]269      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
270      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
271      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
272      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
[3139]273      if (Problem != null) {
[2986]274        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
[3139]275      }
[2986]276    }
[2852]277
[3023]278    private void ParameterizeSolutionsCreator() {
279      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
280      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
[2986]281    }
[3198]282    private void ParameterizeGeneticAlgorithmMainLoop() {
283      GeneticAlgorithmMainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
284      GeneticAlgorithmMainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
285      GeneticAlgorithmMainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
[2986]286    }
287    private void ParameterizeStochasticOperator(IOperator op) {
288      if (op is IStochasticOperator)
289        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
290    }
291    private void ParameterizeSelectors() {
[3680]292      foreach (ISelector selector in SelectorParameter.ValidValues) {
[3048]293        selector.CopySelected = new BoolValue(true);
294        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSizeParameter.Value.Value - ElitesParameter.Value.Value));
[2986]295        ParameterizeStochasticOperator(selector);
296      }
297      if (Problem != null) {
[3680]298        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
[2986]299          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
300          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
301        }
302      }
303    }
[3616]304    private void ParameterizeAnalyzers() {
305      qualityAnalyzer.ResultsParameter.ActualName = "Results";
306      if (Problem != null) {
307        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
308        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
[3662]309        qualityAnalyzer.QualityParameter.Depth = 1;
[3616]310        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
311      }
312    }
[3750]313    private void ParameterizeIterationBasedOperators() {
314      if (Problem != null) {
315        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
316          op.IterationsParameter.ActualName = "Generations";
317          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
318        }
319      }
320    }
[2986]321    private void UpdateCrossovers() {
[3303]322      ICrossover oldCrossover = CrossoverParameter.Value;
323      CrossoverParameter.ValidValues.Clear();
324      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
325        CrossoverParameter.ValidValues.Add(crossover);
326      if (oldCrossover != null) {
327        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
328        if (crossover != null) CrossoverParameter.Value = crossover;
[3076]329      }
[2986]330    }
331    private void UpdateMutators() {
[3303]332      IManipulator oldMutator = MutatorParameter.Value;
333      MutatorParameter.ValidValues.Clear();
334      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
335        MutatorParameter.ValidValues.Add(mutator);
336      if (oldMutator != null) {
337        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
338        if (mutator != null) MutatorParameter.Value = mutator;
[3076]339      }
[2986]340    }
[3616]341    private void UpdateAnalyzers() {
342      Analyzer.Operators.Clear();
343      if (Problem != null) {
[3816]344        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
[3663]345          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
346            param.Depth = 1;
[3616]347          Analyzer.Operators.Add(analyzer);
[3662]348        }
[3616]349      }
[3799]350      Analyzer.Operators.Add(qualityAnalyzer);
[3616]351    }
[2986]352    #endregion
[2]353  }
354}
Note: See TracBrowser for help on using the repository browser.