Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 9198 was 8351, checked in by ascheibe, 12 years ago

#1331 fixed algorithms that couldn't handle Items that they get now from the problem (I overlooked these two cases, all other algorithms/cases have been adapted in the course of ticket #1864)

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