Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ParameterBinding/HeuristicLab.Algorithms.GeneticAlgorithm/3.3/GeneticAlgorithm.cs @ 5760

Last change on this file since 5760 was 4722, checked in by swagner, 14 years ago

Merged cloning refactoring branch back into trunk (#922)

File size: 16.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
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
22using System;
23using System.Linq;
24using HeuristicLab.Analysis;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Optimization;
29using HeuristicLab.Optimization.Operators;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.PluginInfrastructure;
33using HeuristicLab.Random;
34
35namespace HeuristicLab.Algorithms.GeneticAlgorithm {
36  /// <summary>
37  /// A genetic algorithm.
38  /// </summary>
39  [Item("Genetic Algorithm", "A genetic algorithm.")]
40  [Creatable("Algorithms")]
41  [StorableClass]
42  public sealed class GeneticAlgorithm : EngineAlgorithm, IStorableContent {
43    public string Filename { get; set; }
44
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
54
55    #region Parameter Properties
56    private ValueParameter<IntValue> SeedParameter {
57      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
58    }
59    private ValueParameter<BoolValue> SetSeedRandomlyParameter {
60      get { return (ValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
61    }
62    private ValueParameter<IntValue> PopulationSizeParameter {
63      get { return (ValueParameter<IntValue>)Parameters["PopulationSize"]; }
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    }
71    private ValueParameter<PercentValue> MutationProbabilityParameter {
72      get { return (ValueParameter<PercentValue>)Parameters["MutationProbability"]; }
73    }
74    private OptionalConstrainedValueParameter<IManipulator> MutatorParameter {
75      get { return (OptionalConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
76    }
77    private ValueParameter<IntValue> ElitesParameter {
78      get { return (ValueParameter<IntValue>)Parameters["Elites"]; }
79    }
80    private ValueParameter<MultiAnalyzer> AnalyzerParameter {
81      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
82    }
83    private ValueParameter<IntValue> MaximumGenerationsParameter {
84      get { return (ValueParameter<IntValue>)Parameters["MaximumGenerations"]; }
85    }
86    #endregion
87
88    #region Properties
89    public IntValue Seed {
90      get { return SeedParameter.Value; }
91      set { SeedParameter.Value = value; }
92    }
93    public BoolValue SetSeedRandomly {
94      get { return SetSeedRandomlyParameter.Value; }
95      set { SetSeedRandomlyParameter.Value = value; }
96    }
97    public IntValue PopulationSize {
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    }
109    public PercentValue MutationProbability {
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    }
117    public IntValue Elites {
118      get { return ElitesParameter.Value; }
119      set { ElitesParameter.Value = value; }
120    }
121    public MultiAnalyzer Analyzer {
122      get { return AnalyzerParameter.Value; }
123      set { AnalyzerParameter.Value = value; }
124    }
125    public IntValue MaximumGenerations {
126      get { return MaximumGenerationsParameter.Value; }
127      set { MaximumGenerationsParameter.Value = value; }
128    }
129    private RandomCreator RandomCreator {
130      get { return (RandomCreator)OperatorGraph.InitialOperator; }
131    }
132    private SolutionsCreator SolutionsCreator {
133      get { return (SolutionsCreator)RandomCreator.Successor; }
134    }
135    private GeneticAlgorithmMainLoop GeneticAlgorithmMainLoop {
136      get { return (GeneticAlgorithmMainLoop)SolutionsCreator.Successor; }
137    }
138    [Storable]
139    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
140    #endregion
141
142    public GeneticAlgorithm()
143      : base() {
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)));
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."));
149      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
150      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
151      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
152      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
153      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations which should be processed.", new IntValue(1000)));
154
155      RandomCreator randomCreator = new RandomCreator();
156      SolutionsCreator solutionsCreator = new SolutionsCreator();
157      GeneticAlgorithmMainLoop geneticAlgorithmMainLoop = new GeneticAlgorithmMainLoop();
158      OperatorGraph.InitialOperator = randomCreator;
159
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;
165      randomCreator.Successor = solutionsCreator;
166
167      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
168      solutionsCreator.Successor = geneticAlgorithmMainLoop;
169
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;
177      geneticAlgorithmMainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
178      geneticAlgorithmMainLoop.ResultsParameter.ActualName = "Results";
179
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
190      Initialize();
191    }
192    [StorableConstructor]
193    private GeneticAlgorithm(bool deserializing) : base(deserializing) { }
194    [StorableHook(HookType.AfterDeserialization)]
195    private void AfterDeserialization() {
196      Initialize();
197    }
198
199    private GeneticAlgorithm(GeneticAlgorithm original, Cloner cloner)
200      : base(original, cloner) {
201      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
202      Initialize();
203    }
204    public override IDeepCloneable Clone(Cloner cloner) {
205      return new GeneticAlgorithm(this, cloner);
206    }
207
208    public override void Prepare() {
209      if (Problem != null) base.Prepare();
210    }
211
212    #region Events
213    protected override void OnProblemChanged() {
214      ParameterizeStochasticOperator(Problem.SolutionCreator);
215      ParameterizeStochasticOperator(Problem.Evaluator);
216      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
217      ParameterizeSolutionsCreator();
218      ParameterizeGeneticAlgorithmMainLoop();
219      ParameterizeSelectors();
220      ParameterizeAnalyzers();
221      ParameterizeIterationBasedOperators();
222      UpdateCrossovers();
223      UpdateMutators();
224      UpdateAnalyzers();
225      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
226      base.OnProblemChanged();
227    }
228
229    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
230      ParameterizeStochasticOperator(Problem.SolutionCreator);
231      ParameterizeSolutionsCreator();
232      base.Problem_SolutionCreatorChanged(sender, e);
233    }
234    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
235      ParameterizeStochasticOperator(Problem.Evaluator);
236      ParameterizeSolutionsCreator();
237      ParameterizeGeneticAlgorithmMainLoop();
238      ParameterizeSelectors();
239      ParameterizeAnalyzers();
240      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
241      base.Problem_EvaluatorChanged(sender, e);
242    }
243    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
244      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
245      ParameterizeIterationBasedOperators();
246      UpdateCrossovers();
247      UpdateMutators();
248      UpdateAnalyzers();
249      base.Problem_OperatorsChanged(sender, e);
250    }
251    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
252      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
253      ParameterizeSelectors();
254    }
255    private void Elites_ValueChanged(object sender, EventArgs e) {
256      ParameterizeSelectors();
257    }
258    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
259      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
260      ParameterizeSelectors();
261    }
262    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
263      ParameterizeSelectors();
264    }
265    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
266      ParameterizeGeneticAlgorithmMainLoop();
267      ParameterizeSelectors();
268      ParameterizeAnalyzers();
269    }
270    #endregion
271
272    #region Helpers
273    private void Initialize() {
274      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
275      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
276      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
277      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
278      if (Problem != null) {
279        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
280      }
281    }
282
283    private void ParameterizeSolutionsCreator() {
284      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
285      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
286    }
287    private void ParameterizeGeneticAlgorithmMainLoop() {
288      GeneticAlgorithmMainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
289      GeneticAlgorithmMainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
290      GeneticAlgorithmMainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
291    }
292    private void ParameterizeStochasticOperator(IOperator op) {
293      if (op is IStochasticOperator)
294        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
295    }
296    private void ParameterizeSelectors() {
297      foreach (ISelector selector in SelectorParameter.ValidValues) {
298        selector.CopySelected = new BoolValue(true);
299        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSizeParameter.Value.Value - ElitesParameter.Value.Value));
300        ParameterizeStochasticOperator(selector);
301      }
302      if (Problem != null) {
303        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
304          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
305          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
306        }
307      }
308    }
309    private void ParameterizeAnalyzers() {
310      qualityAnalyzer.ResultsParameter.ActualName = "Results";
311      if (Problem != null) {
312        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
313        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
314        qualityAnalyzer.QualityParameter.Depth = 1;
315        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
316      }
317    }
318    private void ParameterizeIterationBasedOperators() {
319      if (Problem != null) {
320        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
321          op.IterationsParameter.ActualName = "Generations";
322          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
323        }
324      }
325    }
326    private void UpdateCrossovers() {
327      ICrossover oldCrossover = CrossoverParameter.Value;
328      CrossoverParameter.ValidValues.Clear();
329      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
330        CrossoverParameter.ValidValues.Add(crossover);
331      if (oldCrossover != null) {
332        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
333        if (crossover != null) CrossoverParameter.Value = crossover;
334      }
335    }
336    private void UpdateMutators() {
337      IManipulator oldMutator = MutatorParameter.Value;
338      MutatorParameter.ValidValues.Clear();
339      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
340        MutatorParameter.ValidValues.Add(mutator);
341      if (oldMutator != null) {
342        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
343        if (mutator != null) MutatorParameter.Value = mutator;
344      }
345    }
346    private void UpdateAnalyzers() {
347      Analyzer.Operators.Clear();
348      if (Problem != null) {
349        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
350          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
351            param.Depth = 1;
352          Analyzer.Operators.Add(analyzer);
353        }
354      }
355      Analyzer.Operators.Add(qualityAnalyzer);
356    }
357    #endregion
358  }
359}
Note: See TracBrowser for help on using the repository browser.