Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6451 was 6439, checked in by gkronber, 14 years ago

#1553: implemented unit test to create and run the symbolic regression sample (towerData.txt)

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