Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 9553 was 9553, checked in by mkommend, 12 years ago

#2038: Added possibility to reevaluate elites in the GA.

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