Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Algorithms.GeneticAlgorithm/3.3/GeneticAlgorithm.cs @ 12531

Last change on this file since 12531 was 6760, checked in by epitzer, 13 years ago

#1530 integrate changes from trunk

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