Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Algorithms.GeneticAlgorithm/3.3/GeneticAlgorithm.cs @ 18023

Last change on this file since 18023 was 17198, checked in by mkommend, 5 years ago

#3020: Adapated AfterDeserializationHook of genetic algorithms to check if the mutator parameter already has the correct type.
In detail the following algorithms have been adapted: ALPS-GA, ALPS-OSGA, GA, Island-GA, NSGA-2, Island-OSGA, OSGA, SASEGASA.

File size: 20.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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 HEAL.Attic;
25using HeuristicLab.Analysis;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Operators;
30using HeuristicLab.Optimization;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Random;
35
36namespace HeuristicLab.Algorithms.GeneticAlgorithm {
37  /// <summary>
38  /// A genetic algorithm.
39  /// </summary>
40  [Item("Genetic Algorithm (GA)", "A genetic algorithm.")]
41  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 100)]
42  [StorableType("B63D21BD-D6AE-474B-A319-AC92CCB30AF6")]
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 ConstrainedValueParameter<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(StorableConstructorFlag _) : base(_) { }
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
224      var optionalMutatorParameter = MutatorParameter as OptionalConstrainedValueParameter<IManipulator>;
225      var mutatorParameter = MutatorParameter as ConstrainedValueParameter<IManipulator>;
226      if (mutatorParameter == null && optionalMutatorParameter != null) {
227        Parameters.Remove(optionalMutatorParameter);
228        Parameters.Add(new ConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
229        foreach (var m in optionalMutatorParameter.ValidValues)
230          MutatorParameter.ValidValues.Add(m);
231        if (optionalMutatorParameter.Value == null) MutationProbability.Value = 0; // to guarantee that the old configuration results in the same behavior
232        else Mutator = optionalMutatorParameter.Value;
233        optionalMutatorParameter.ValidValues.Clear(); // to avoid dangling references to the old parameter its valid values are cleared
234      }
235      #endregion
236
237      Initialize();
238    }
239
240
241
242    private GeneticAlgorithm(GeneticAlgorithm original, Cloner cloner)
243      : base(original, cloner) {
244      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
245      Initialize();
246    }
247    public override IDeepCloneable Clone(Cloner cloner) {
248      return new GeneticAlgorithm(this, cloner);
249    }
250
251    public override void Prepare() {
252      if (Problem != null) base.Prepare();
253    }
254
255    #region Events
256    protected override void OnProblemChanged() {
257      ParameterizeStochasticOperator(Problem.SolutionCreator);
258      ParameterizeStochasticOperator(Problem.Evaluator);
259      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
260      ParameterizeSolutionsCreator();
261      ParameterizeGeneticAlgorithmMainLoop();
262      ParameterizeSelectors();
263      ParameterizeAnalyzers();
264      ParameterizeIterationBasedOperators();
265      UpdateCrossovers();
266      UpdateMutators();
267      UpdateAnalyzers();
268      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
269      base.OnProblemChanged();
270    }
271
272    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
273      ParameterizeStochasticOperator(Problem.SolutionCreator);
274      ParameterizeSolutionsCreator();
275      base.Problem_SolutionCreatorChanged(sender, e);
276    }
277    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
278      ParameterizeStochasticOperator(Problem.Evaluator);
279      ParameterizeSolutionsCreator();
280      ParameterizeGeneticAlgorithmMainLoop();
281      ParameterizeSelectors();
282      ParameterizeAnalyzers();
283      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
284      base.Problem_EvaluatorChanged(sender, e);
285    }
286    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
287      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
288      ParameterizeIterationBasedOperators();
289      UpdateCrossovers();
290      UpdateMutators();
291      UpdateAnalyzers();
292      base.Problem_OperatorsChanged(sender, e);
293    }
294    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
295      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
296      ParameterizeSelectors();
297    }
298    private void Elites_ValueChanged(object sender, EventArgs e) {
299      ParameterizeSelectors();
300    }
301
302    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
303      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
304      ParameterizeSelectors();
305    }
306    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
307      ParameterizeSelectors();
308    }
309    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
310      ParameterizeGeneticAlgorithmMainLoop();
311      ParameterizeSelectors();
312      ParameterizeAnalyzers();
313    }
314    #endregion
315
316    #region Helpers
317    private void Initialize() {
318      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
319      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
320      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
321      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
322      if (Problem != null) {
323        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
324      }
325    }
326
327    private void ParameterizeSolutionsCreator() {
328      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
329      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
330    }
331    private void ParameterizeGeneticAlgorithmMainLoop() {
332      GeneticAlgorithmMainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
333      GeneticAlgorithmMainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
334      GeneticAlgorithmMainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
335    }
336    private void ParameterizeStochasticOperator(IOperator op) {
337      IStochasticOperator stochasticOp = op as IStochasticOperator;
338      if (stochasticOp != null) {
339        stochasticOp.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
340        stochasticOp.RandomParameter.Hidden = true;
341      }
342    }
343    private void ParameterizeSelectors() {
344      foreach (ISelector selector in SelectorParameter.ValidValues) {
345        selector.CopySelected = new BoolValue(true);
346        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSizeParameter.Value.Value - ElitesParameter.Value.Value));
347        selector.NumberOfSelectedSubScopesParameter.Hidden = true;
348        ParameterizeStochasticOperator(selector);
349      }
350      if (Problem != null) {
351        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
352          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
353          selector.MaximizationParameter.Hidden = true;
354          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
355          selector.QualityParameter.Hidden = true;
356        }
357      }
358    }
359    private void ParameterizeAnalyzers() {
360      qualityAnalyzer.ResultsParameter.ActualName = "Results";
361      qualityAnalyzer.ResultsParameter.Hidden = true;
362      if (Problem != null) {
363        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
364        qualityAnalyzer.MaximizationParameter.Hidden = true;
365        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
366        qualityAnalyzer.QualityParameter.Depth = 1;
367        qualityAnalyzer.QualityParameter.Hidden = true;
368        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
369        qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
370      }
371    }
372    private void ParameterizeIterationBasedOperators() {
373      if (Problem != null) {
374        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
375          op.IterationsParameter.ActualName = "Generations";
376          op.IterationsParameter.Hidden = true;
377          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
378          op.MaximumIterationsParameter.Hidden = true;
379        }
380      }
381    }
382    private void UpdateCrossovers() {
383      ICrossover oldCrossover = CrossoverParameter.Value;
384      CrossoverParameter.ValidValues.Clear();
385      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
386
387      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
388        CrossoverParameter.ValidValues.Add(crossover);
389
390      if (oldCrossover != null) {
391        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
392        if (crossover != null) CrossoverParameter.Value = crossover;
393        else oldCrossover = null;
394      }
395      if (oldCrossover == null && defaultCrossover != null)
396        CrossoverParameter.Value = defaultCrossover;
397    }
398    private void UpdateMutators() {
399      IManipulator oldMutator = MutatorParameter.Value;
400      MutatorParameter.ValidValues.Clear();
401      IManipulator defaultMutator = Problem.Operators.OfType<IManipulator>().FirstOrDefault();
402
403      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
404        MutatorParameter.ValidValues.Add(mutator);
405
406      if (oldMutator != null) {
407        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
408        if (mutator != null) MutatorParameter.Value = mutator;
409        else oldMutator = null;
410      }
411
412      if (oldMutator == null && defaultMutator != null)
413        MutatorParameter.Value = defaultMutator;
414    }
415    private void UpdateAnalyzers() {
416      Analyzer.Operators.Clear();
417      if (Problem != null) {
418        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
419          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
420            param.Depth = 1;
421          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
422        }
423      }
424      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
425    }
426    private GeneticAlgorithmMainLoop FindMainLoop(IOperator start) {
427      IOperator mainLoop = start;
428      while (mainLoop != null && !(mainLoop is GeneticAlgorithmMainLoop))
429        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
430      if (mainLoop == null) return null;
431      else return (GeneticAlgorithmMainLoop)mainLoop;
432    }
433    #endregion
434  }
435}
Note: See TracBrowser for help on using the repository browser.