Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5352 was 5352, checked in by abeham, 14 years ago

#1333

  • Removed changes to IntCounter that would make it thread-safe, if a thread-safe operator is needed a separate one should be implemented
  • Moved counting of evaluated solutions out of the parallel region
File size: 17.2 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.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 : EngineAlgorithm, IStorableContent {
44    public string Filename { get; set; }
45
46    #region Problem Properties
47    public override Type ProblemType {
48      get { return typeof(ISingleObjectiveProblem); }
49    }
50    public new ISingleObjectiveProblem Problem {
51      get { return (ISingleObjectiveProblem)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    private ConstrainedValueParameter<ISelector> SelectorParameter {
67      get { return (ConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
68    }
69    private ConstrainedValueParameter<ICrossover> CrossoverParameter {
70      get { return (ConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
71    }
72    private ValueParameter<PercentValue> MutationProbabilityParameter {
73      get { return (ValueParameter<PercentValue>)Parameters["MutationProbability"]; }
74    }
75    private OptionalConstrainedValueParameter<IManipulator> MutatorParameter {
76      get { return (OptionalConstrainedValueParameter<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 (GeneticAlgorithmMainLoop)((SubScopesCounter)SolutionsCreator.Successor).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      GeneticAlgorithmMainLoop geneticAlgorithmMainLoop = new GeneticAlgorithmMainLoop();
160      OperatorGraph.InitialOperator = randomCreator;
161
162      randomCreator.RandomParameter.ActualName = "Random";
163      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
164      randomCreator.SeedParameter.Value = null;
165      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
166      randomCreator.SetSeedRandomlyParameter.Value = null;
167      randomCreator.Successor = solutionsCreator;
168
169      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
170      solutionsCreator.Successor = subScopesCounter;
171
172      subScopesCounter.Name = "Initialize EvaluatedSolutions";
173      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
174      subScopesCounter.Successor = geneticAlgorithmMainLoop;
175
176      geneticAlgorithmMainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
177      geneticAlgorithmMainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
178      geneticAlgorithmMainLoop.ElitesParameter.ActualName = ElitesParameter.Name;
179      geneticAlgorithmMainLoop.MaximumGenerationsParameter.ActualName = MaximumGenerationsParameter.Name;
180      geneticAlgorithmMainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
181      geneticAlgorithmMainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
182      geneticAlgorithmMainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
183      geneticAlgorithmMainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
184      geneticAlgorithmMainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
185      geneticAlgorithmMainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
186      geneticAlgorithmMainLoop.ResultsParameter.ActualName = "Results";
187
188      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is IMultiObjectiveSelector)).OrderBy(x => x.Name))
189        SelectorParameter.ValidValues.Add(selector);
190      ISelector proportionalSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("ProportionalSelector"));
191      if (proportionalSelector != null) SelectorParameter.Value = proportionalSelector;
192      ParameterizeSelectors();
193
194      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
195      ParameterizeAnalyzers();
196      UpdateAnalyzers();
197
198      Initialize();
199    }
200    [StorableConstructor]
201    private GeneticAlgorithm(bool deserializing) : base(deserializing) { }
202    [StorableHook(HookType.AfterDeserialization)]
203    private void AfterDeserialization() {
204      Initialize();
205    }
206
207    private GeneticAlgorithm(GeneticAlgorithm original, Cloner cloner)
208      : base(original, cloner) {
209      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
210      Initialize();
211    }
212    public override IDeepCloneable Clone(Cloner cloner) {
213      return new GeneticAlgorithm(this, cloner);
214    }
215
216    public override void Prepare() {
217      if (Problem != null) base.Prepare();
218    }
219
220    #region Events
221    protected override void OnProblemChanged() {
222      ParameterizeStochasticOperator(Problem.SolutionCreator);
223      ParameterizeStochasticOperator(Problem.Evaluator);
224      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
225      ParameterizeSolutionsCreator();
226      ParameterizeGeneticAlgorithmMainLoop();
227      ParameterizeSelectors();
228      ParameterizeAnalyzers();
229      ParameterizeIterationBasedOperators();
230      UpdateCrossovers();
231      UpdateMutators();
232      UpdateAnalyzers();
233      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
234      base.OnProblemChanged();
235    }
236
237    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
238      ParameterizeStochasticOperator(Problem.SolutionCreator);
239      ParameterizeSolutionsCreator();
240      base.Problem_SolutionCreatorChanged(sender, e);
241    }
242    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
243      ParameterizeStochasticOperator(Problem.Evaluator);
244      ParameterizeSolutionsCreator();
245      ParameterizeGeneticAlgorithmMainLoop();
246      ParameterizeSelectors();
247      ParameterizeAnalyzers();
248      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
249      base.Problem_EvaluatorChanged(sender, e);
250    }
251    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
252      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
253      ParameterizeIterationBasedOperators();
254      UpdateCrossovers();
255      UpdateMutators();
256      UpdateAnalyzers();
257      base.Problem_OperatorsChanged(sender, e);
258    }
259    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
260      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
261      ParameterizeSelectors();
262    }
263    private void Elites_ValueChanged(object sender, EventArgs e) {
264      ParameterizeSelectors();
265    }
266
267    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
268      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
269      ParameterizeSelectors();
270    }
271    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
272      ParameterizeSelectors();
273    }
274    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
275      ParameterizeGeneticAlgorithmMainLoop();
276      ParameterizeSelectors();
277      ParameterizeAnalyzers();
278    }
279    #endregion
280
281    #region Helpers
282    private void Initialize() {
283      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
284      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
285      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
286      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
287      if (Problem != null) {
288        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
289      }
290    }
291
292    private void ParameterizeSolutionsCreator() {
293      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
294      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
295    }
296    private void ParameterizeGeneticAlgorithmMainLoop() {
297      GeneticAlgorithmMainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
298      GeneticAlgorithmMainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
299      GeneticAlgorithmMainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
300    }
301    private void ParameterizeStochasticOperator(IOperator op) {
302      if (op is IStochasticOperator)
303        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
304    }
305    private void ParameterizeSelectors() {
306      foreach (ISelector selector in SelectorParameter.ValidValues) {
307        selector.CopySelected = new BoolValue(true);
308        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSizeParameter.Value.Value - ElitesParameter.Value.Value));
309        ParameterizeStochasticOperator(selector);
310      }
311      if (Problem != null) {
312        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
313          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
314          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
315        }
316      }
317    }
318    private void ParameterizeAnalyzers() {
319      qualityAnalyzer.ResultsParameter.ActualName = "Results";
320      if (Problem != null) {
321        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
322        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
323        qualityAnalyzer.QualityParameter.Depth = 1;
324        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
325      }
326    }
327    private void ParameterizeIterationBasedOperators() {
328      if (Problem != null) {
329        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
330          op.IterationsParameter.ActualName = "Generations";
331          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
332        }
333      }
334    }
335    private void UpdateCrossovers() {
336      ICrossover oldCrossover = CrossoverParameter.Value;
337      CrossoverParameter.ValidValues.Clear();
338      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
339        CrossoverParameter.ValidValues.Add(crossover);
340      if (oldCrossover != null) {
341        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
342        if (crossover != null) CrossoverParameter.Value = crossover;
343      }
344    }
345    private void UpdateMutators() {
346      IManipulator oldMutator = MutatorParameter.Value;
347      MutatorParameter.ValidValues.Clear();
348      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
349        MutatorParameter.ValidValues.Add(mutator);
350      if (oldMutator != null) {
351        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
352        if (mutator != null) MutatorParameter.Value = mutator;
353      }
354    }
355    private void UpdateAnalyzers() {
356      Analyzer.Operators.Clear();
357      if (Problem != null) {
358        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
359          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
360            param.Depth = 1;
361          Analyzer.Operators.Add(analyzer);
362        }
363      }
364      Analyzer.Operators.Add(qualityAnalyzer);
365    }
366    #endregion
367  }
368}
Note: See TracBrowser for help on using the repository browser.