Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1247: added duplication control

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