Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4311 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

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