Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7403 was 7259, checked in by swagner, 13 years ago

Updated year of copyrights to 2012 (#1716)

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