Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.SGA/3.3/SGA.cs @ 3039

Last change on this file since 3039 was 3023, checked in by swagner, 15 years ago

Renamed PopulationCreator to SolutionsCreator (#911)

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