Free cookie consent management tool by TermsFeed Policy Generator

source: branches/LogResidualEvaluator/HeuristicLab.Algorithms.GeneticAlgorithm/3.3/GeneticAlgorithm.cs @ 10202

Last change on this file since 10202 was 9592, checked in by abeham, 11 years ago

#2038: Added tagging comment

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