Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RAPGA/HeuristicLab.Algorithms.RAPGA/3.3/RAPGA.cs @ 8313

Last change on this file since 8313 was 8313, checked in by jkarder, 12 years ago

#1247: initial commit

File size: 18.4 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.RAPGA {
37  /// <summary>
38  /// A relevant alleles preserving genetic algorithm.
39  /// </summary>
40  [Item("RAPGA", "A relevant alleles preserving genetic algorithm.")]
41  [Creatable("Algorithms")]
42  [StorableClass]
43  public sealed class RAPGA : 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 RAPGAMainLoop RAPGAMainLoop {
137      get { return FindMainLoop(SolutionsCreator.Successor); }
138    }
139    [Storable]
140    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
141    #endregion
142
143    [StorableConstructor]
144    private RAPGA(bool deserializing) : base(deserializing) { }
145    [StorableHook(HookType.AfterDeserialization)]
146    private void AfterDeserialization() { Initialize(); }
147    private RAPGA(RAPGA original, Cloner cloner)
148      : base(original, cloner) {
149      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
150      Initialize();
151    }
152    public RAPGA()
153      : base() {
154      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
155      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
156      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions.", new IntValue(100)));
157      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
158      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
159      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
160      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
161      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
162      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
163      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations which should be processed.", new IntValue(1000)));
164
165      RandomCreator randomCreator = new RandomCreator();
166      SolutionsCreator solutionsCreator = new SolutionsCreator();
167      SubScopesCounter subScopesCounter = new SubScopesCounter();
168      ResultsCollector resultsCollector = new ResultsCollector();
169      RAPGAMainLoop mainLoop = new RAPGAMainLoop();
170      OperatorGraph.InitialOperator = randomCreator;
171
172      randomCreator.RandomParameter.ActualName = "Random";
173      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
174      randomCreator.SeedParameter.Value = null;
175      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
176      randomCreator.SetSeedRandomlyParameter.Value = null;
177      randomCreator.Successor = solutionsCreator;
178
179      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
180      solutionsCreator.Successor = subScopesCounter;
181
182      subScopesCounter.Name = "Initialize EvaluatedSolutions";
183      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
184      subScopesCounter.Successor = resultsCollector;
185
186      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
187      resultsCollector.ResultsParameter.ActualName = "Results";
188      resultsCollector.Successor = mainLoop;
189
190      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
191      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
192      mainLoop.ElitesParameter.ActualName = ElitesParameter.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    public override IDeepCloneable Clone(Cloner cloner) {
215      return new RAPGA(this, cloner);
216    }
217
218    public override void Prepare() {
219      if (Problem != null) base.Prepare();
220    }
221
222    #region Events
223    protected override void OnProblemChanged() {
224      ParameterizeStochasticOperator(Problem.SolutionCreator);
225      ParameterizeStochasticOperator(Problem.Evaluator);
226      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
227      ParameterizeSolutionsCreator();
228      ParameterizeGeneticAlgorithmMainLoop();
229      ParameterizeSelectors();
230      ParameterizeAnalyzers();
231      ParameterizeIterationBasedOperators();
232      UpdateCrossovers();
233      UpdateMutators();
234      UpdateAnalyzers();
235      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
236      base.OnProblemChanged();
237    }
238
239    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
240      ParameterizeStochasticOperator(Problem.SolutionCreator);
241      ParameterizeSolutionsCreator();
242      base.Problem_SolutionCreatorChanged(sender, e);
243    }
244    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
245      ParameterizeStochasticOperator(Problem.Evaluator);
246      ParameterizeSolutionsCreator();
247      ParameterizeGeneticAlgorithmMainLoop();
248      ParameterizeSelectors();
249      ParameterizeAnalyzers();
250      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
251      base.Problem_EvaluatorChanged(sender, e);
252    }
253    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
254      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
255      ParameterizeIterationBasedOperators();
256      UpdateCrossovers();
257      UpdateMutators();
258      UpdateAnalyzers();
259      base.Problem_OperatorsChanged(sender, e);
260    }
261    private void ElitesParameter_ValueChanged(object sender, EventArgs e) {
262      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
263      ParameterizeSelectors();
264    }
265    private void Elites_ValueChanged(object sender, EventArgs e) {
266      ParameterizeSelectors();
267    }
268
269    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
270      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
271      ParameterizeSelectors();
272    }
273    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
274      ParameterizeSelectors();
275    }
276    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
277      ParameterizeGeneticAlgorithmMainLoop();
278      ParameterizeSelectors();
279      ParameterizeAnalyzers();
280    }
281    #endregion
282
283    #region Helpers
284    private void Initialize() {
285      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
286      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
287      ElitesParameter.ValueChanged += new EventHandler(ElitesParameter_ValueChanged);
288      Elites.ValueChanged += new EventHandler(Elites_ValueChanged);
289      if (Problem != null) {
290        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
291      }
292    }
293
294    private void ParameterizeSolutionsCreator() {
295      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
296      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
297    }
298    private void ParameterizeGeneticAlgorithmMainLoop() {
299      RAPGAMainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
300      RAPGAMainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
301      RAPGAMainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
302    }
303    private void ParameterizeStochasticOperator(IOperator op) {
304      IStochasticOperator stochasticOp = op as IStochasticOperator;
305      if (stochasticOp != null) {
306        stochasticOp.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
307        stochasticOp.RandomParameter.Hidden = true;
308      }
309    }
310    private void ParameterizeSelectors() {
311      foreach (ISelector selector in SelectorParameter.ValidValues) {
312        selector.CopySelected = new BoolValue(true);
313        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSizeParameter.Value.Value - ElitesParameter.Value.Value));
314        selector.NumberOfSelectedSubScopesParameter.Hidden = true;
315        ParameterizeStochasticOperator(selector);
316      }
317      if (Problem != null) {
318        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
319          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
320          selector.MaximizationParameter.Hidden = true;
321          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
322          selector.QualityParameter.Hidden = true;
323        }
324      }
325    }
326    private void ParameterizeAnalyzers() {
327      qualityAnalyzer.ResultsParameter.ActualName = "Results";
328      qualityAnalyzer.ResultsParameter.Hidden = true;
329      if (Problem != null) {
330        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
331        qualityAnalyzer.MaximizationParameter.Hidden = true;
332        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
333        qualityAnalyzer.QualityParameter.Depth = 1;
334        qualityAnalyzer.QualityParameter.Hidden = true;
335        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
336        qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
337      }
338    }
339    private void ParameterizeIterationBasedOperators() {
340      if (Problem != null) {
341        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
342          op.IterationsParameter.ActualName = "Generations";
343          op.IterationsParameter.Hidden = true;
344          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
345          op.MaximumIterationsParameter.Hidden = true;
346        }
347      }
348    }
349    private void UpdateCrossovers() {
350      ICrossover oldCrossover = CrossoverParameter.Value;
351      CrossoverParameter.ValidValues.Clear();
352      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
353
354      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
355        CrossoverParameter.ValidValues.Add(crossover);
356
357      if (oldCrossover != null) {
358        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
359        if (crossover != null) CrossoverParameter.Value = crossover;
360        else oldCrossover = null;
361      }
362      if (oldCrossover == null && defaultCrossover != null)
363        CrossoverParameter.Value = defaultCrossover;
364    }
365    private void UpdateMutators() {
366      IManipulator oldMutator = MutatorParameter.Value;
367      MutatorParameter.ValidValues.Clear();
368      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
369        MutatorParameter.ValidValues.Add(mutator);
370      if (oldMutator != null) {
371        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
372        if (mutator != null) MutatorParameter.Value = mutator;
373      }
374    }
375    private void UpdateAnalyzers() {
376      Analyzer.Operators.Clear();
377      if (Problem != null) {
378        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
379          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
380            param.Depth = 1;
381          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
382        }
383      }
384      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
385    }
386    private RAPGAMainLoop FindMainLoop(IOperator start) {
387      IOperator mainLoop = start;
388      while (mainLoop != null && !(mainLoop is RAPGAMainLoop))
389        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
390      if (mainLoop == null) return null;
391      else return (RAPGAMainLoop)mainLoop;
392    }
393    #endregion
394  }
395}
Note: See TracBrowser for help on using the repository browser.