Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5502 was 5445, checked in by swagner, 14 years ago

Updated year of copyrights (#1406)

File size: 17.6 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;
[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]
[4437]43  public sealed class GeneticAlgorithm : EngineAlgorithm, IStorableContent {
44    public string Filename { get; set; }
45
[2986]46    #region Problem Properties
47    public override Type ProblemType {
48      get { return typeof(ISingleObjectiveProblem); }
49    }
50    public new ISingleObjectiveProblem Problem {
51      get { return (ISingleObjectiveProblem)base.Problem; }
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    }
66    private ConstrainedValueParameter<ISelector> SelectorParameter {
67      get { return (ConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
68    }
69    private ConstrainedValueParameter<ICrossover> CrossoverParameter {
70      get { return (ConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
71    }
[3095]72    private ValueParameter<PercentValue> MutationProbabilityParameter {
73      get { return (ValueParameter<PercentValue>)Parameters["MutationProbability"]; }
[2986]74    }
75    private OptionalConstrainedValueParameter<IManipulator> MutatorParameter {
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) {
307      if (op is IStochasticOperator)
308        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
309    }
310    private void ParameterizeSelectors() {
[3680]311      foreach (ISelector selector in SelectorParameter.ValidValues) {
[3048]312        selector.CopySelected = new BoolValue(true);
313        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSizeParameter.Value.Value - ElitesParameter.Value.Value));
[2986]314        ParameterizeStochasticOperator(selector);
315      }
316      if (Problem != null) {
[3680]317        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
[2986]318          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
319          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
320        }
321      }
322    }
[3616]323    private void ParameterizeAnalyzers() {
324      qualityAnalyzer.ResultsParameter.ActualName = "Results";
325      if (Problem != null) {
326        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
327        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
[3662]328        qualityAnalyzer.QualityParameter.Depth = 1;
[3616]329        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
330      }
331    }
[3750]332    private void ParameterizeIterationBasedOperators() {
333      if (Problem != null) {
334        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
335          op.IterationsParameter.ActualName = "Generations";
336          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
337        }
338      }
339    }
[2986]340    private void UpdateCrossovers() {
[3303]341      ICrossover oldCrossover = CrossoverParameter.Value;
342      CrossoverParameter.ValidValues.Clear();
343      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
344        CrossoverParameter.ValidValues.Add(crossover);
345      if (oldCrossover != null) {
346        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
347        if (crossover != null) CrossoverParameter.Value = crossover;
[3076]348      }
[2986]349    }
350    private void UpdateMutators() {
[3303]351      IManipulator oldMutator = MutatorParameter.Value;
352      MutatorParameter.ValidValues.Clear();
353      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
354        MutatorParameter.ValidValues.Add(mutator);
355      if (oldMutator != null) {
356        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
357        if (mutator != null) MutatorParameter.Value = mutator;
[3076]358      }
[2986]359    }
[3616]360    private void UpdateAnalyzers() {
361      Analyzer.Operators.Clear();
362      if (Problem != null) {
[3816]363        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
[3663]364          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
365            param.Depth = 1;
[3616]366          Analyzer.Operators.Add(analyzer);
[3662]367        }
[3616]368      }
[3799]369      Analyzer.Operators.Add(qualityAnalyzer);
[3616]370    }
[5366]371    private GeneticAlgorithmMainLoop FindMainLoop(IOperator start) {
372      IOperator mainLoop = start;
373      while (mainLoop != null && !(mainLoop is GeneticAlgorithmMainLoop))
374        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
375      if (mainLoop == null) return null;
376      else return (GeneticAlgorithmMainLoop)mainLoop;
377    }
[2986]378    #endregion
[2]379  }
380}
Note: See TracBrowser for help on using the repository browser.