Free cookie consent management tool by TermsFeed Policy Generator

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

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

Implemented !IStorableContent separately for each algorithm (#1193)

File size: 16.6 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
195    public override IDeepCloneable Clone(Cloner cloner) {
196      GeneticAlgorithm clone = (GeneticAlgorithm)base.Clone(cloner);
197      clone.qualityAnalyzer = (BestAverageWorstQualityAnalyzer)cloner.Clone(qualityAnalyzer);
198      clone.Initialize();
199      return clone;
200    }
201
202    public override void Prepare() {
203      if (Problem != null) base.Prepare();
204    }
205
206    #region Events
207    protected override void OnProblemChanged() {
208      ParameterizeStochasticOperator(Problem.SolutionCreator);
209      ParameterizeStochasticOperator(Problem.Evaluator);
210      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
211      ParameterizeSolutionsCreator();
212      ParameterizeGeneticAlgorithmMainLoop();
213      ParameterizeSelectors();
214      ParameterizeAnalyzers();
215      ParameterizeIterationBasedOperators();
216      UpdateCrossovers();
217      UpdateMutators();
218      UpdateAnalyzers();
219      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
220      base.OnProblemChanged();
221    }
222
223    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
224      ParameterizeStochasticOperator(Problem.SolutionCreator);
225      ParameterizeSolutionsCreator();
226      base.Problem_SolutionCreatorChanged(sender, e);
227    }
228    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
229      ParameterizeStochasticOperator(Problem.Evaluator);
230      ParameterizeSolutionsCreator();
231      ParameterizeGeneticAlgorithmMainLoop();
232      ParameterizeSelectors();
233      ParameterizeAnalyzers();
234      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
235      base.Problem_EvaluatorChanged(sender, e);
236    }
237    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
238      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
239      ParameterizeIterationBasedOperators();
240      UpdateCrossovers();
241      UpdateMutators();
242      UpdateAnalyzers();
243      base.Problem_OperatorsChanged(sender, e);
244    }
245    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
246      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
247      ParameterizeSelectors();
248    }
249    private void Elites_ValueChanged(object sender, EventArgs e) {
250      ParameterizeSelectors();
251    }
252    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
253      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
254      ParameterizeSelectors();
255    }
256    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
257      ParameterizeSelectors();
258    }
259    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
260      ParameterizeGeneticAlgorithmMainLoop();
261      ParameterizeSelectors();
262      ParameterizeAnalyzers();
263    }
264    #endregion
265
266    #region Helpers
267    [StorableHook(HookType.AfterDeserialization)]
268    private void Initialize() {
269      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
270      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
271      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
272      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
273      if (Problem != null) {
274        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
275      }
276    }
277
278    private void ParameterizeSolutionsCreator() {
279      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
280      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
281    }
282    private void ParameterizeGeneticAlgorithmMainLoop() {
283      GeneticAlgorithmMainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
284      GeneticAlgorithmMainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
285      GeneticAlgorithmMainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
286    }
287    private void ParameterizeStochasticOperator(IOperator op) {
288      if (op is IStochasticOperator)
289        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
290    }
291    private void ParameterizeSelectors() {
292      foreach (ISelector selector in SelectorParameter.ValidValues) {
293        selector.CopySelected = new BoolValue(true);
294        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSizeParameter.Value.Value - ElitesParameter.Value.Value));
295        ParameterizeStochasticOperator(selector);
296      }
297      if (Problem != null) {
298        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
299          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
300          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
301        }
302      }
303    }
304    private void ParameterizeAnalyzers() {
305      qualityAnalyzer.ResultsParameter.ActualName = "Results";
306      if (Problem != null) {
307        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
308        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
309        qualityAnalyzer.QualityParameter.Depth = 1;
310        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
311      }
312    }
313    private void ParameterizeIterationBasedOperators() {
314      if (Problem != null) {
315        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
316          op.IterationsParameter.ActualName = "Generations";
317          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
318        }
319      }
320    }
321    private void UpdateCrossovers() {
322      ICrossover oldCrossover = CrossoverParameter.Value;
323      CrossoverParameter.ValidValues.Clear();
324      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
325        CrossoverParameter.ValidValues.Add(crossover);
326      if (oldCrossover != null) {
327        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
328        if (crossover != null) CrossoverParameter.Value = crossover;
329      }
330    }
331    private void UpdateMutators() {
332      IManipulator oldMutator = MutatorParameter.Value;
333      MutatorParameter.ValidValues.Clear();
334      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
335        MutatorParameter.ValidValues.Add(mutator);
336      if (oldMutator != null) {
337        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
338        if (mutator != null) MutatorParameter.Value = mutator;
339      }
340    }
341    private void UpdateAnalyzers() {
342      Analyzer.Operators.Clear();
343      if (Problem != null) {
344        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
345          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
346            param.Depth = 1;
347          Analyzer.Operators.Add(analyzer);
348        }
349      }
350      Analyzer.Operators.Add(qualityAnalyzer);
351    }
352    #endregion
353  }
354}
Note: See TracBrowser for help on using the repository browser.