Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Algorithms.NSGA2/3.3/NSGA2.cs @ 11868

Last change on this file since 11868 was 6228, checked in by epitzer, 14 years ago

check hooks by method name only (#1530)

File size: 19.6 KB
RevLine 
[4012]1#region License Information
2/* HeuristicLab
[5445]3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[4012]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;
[4017]23using System.Linq;
[4068]24using HeuristicLab.Analysis;
[4012]25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
[5356]28using HeuristicLab.Operators;
[4012]29using HeuristicLab.Optimization;
[4068]30using HeuristicLab.Optimization.Operators;
[4012]31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[4068]33using HeuristicLab.PluginInfrastructure;
[4017]34using HeuristicLab.Random;
[4012]35
36namespace HeuristicLab.Algorithms.NSGA2 {
37  /// <summary>
38  /// The Nondominated Sorting Genetic Algorithm II was introduced in Deb et al. 2002. A Fast and Elitist Multiobjective Genetic Algorithm: NSGA-II. IEEE Transactions on Evolutionary Computation, 6(2), pp. 182-197.
39  /// </summary>
[4017]40  [Item("NSGA-II", "The Nondominated Sorting Genetic Algorithm II was introduced in Deb et al. 2002. A Fast and Elitist Multiobjective Genetic Algorithm: NSGA-II. IEEE Transactions on Evolutionary Computation, 6(2), pp. 182-197.")]
[4012]41  [Creatable("Algorithms")]
42  [StorableClass]
[5809]43  public class NSGA2 : HeuristicOptimizationEngineAlgorithm, IStorableContent {
[5366]44    public string Filename { get; set; }
45
[4012]46    #region Problem Properties
47    public override Type ProblemType {
[5809]48      get { return typeof(IMultiObjectiveHeuristicOptimizationProblem); }
[4012]49    }
[5809]50    public new IMultiObjectiveHeuristicOptimizationProblem Problem {
51      get { return (IMultiObjectiveHeuristicOptimizationProblem)base.Problem; }
[4012]52      set { base.Problem = value; }
53    }
54    #endregion
55
56    #region Parameter Properties
[4017]57    private ValueParameter<IntValue> SeedParameter {
58      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
[4012]59    }
[4017]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 ValueParameter<PercentValue> CrossoverProbabilityParameter {
70      get { return (ValueParameter<PercentValue>)Parameters["CrossoverProbability"]; }
71    }
72    private ConstrainedValueParameter<ICrossover> CrossoverParameter {
73      get { return (ConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
74    }
75    private ValueParameter<PercentValue> MutationProbabilityParameter {
76      get { return (ValueParameter<PercentValue>)Parameters["MutationProbability"]; }
77    }
78    private OptionalConstrainedValueParameter<IManipulator> MutatorParameter {
79      get { return (OptionalConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
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    }
[4514]87    private ValueParameter<IntValue> SelectedParentsParameter {
88      get { return (ValueParameter<IntValue>)Parameters["SelectedParents"]; }
89    }
[4012]90    #endregion
91
92    #region Properties
[4017]93    public IntValue Seed {
94      get { return SeedParameter.Value; }
95      set { SeedParameter.Value = value; }
96    }
97    public BoolValue SetSeedRandomly {
98      get { return SetSeedRandomlyParameter.Value; }
99      set { SetSeedRandomlyParameter.Value = value; }
100    }
101    public IntValue PopulationSize {
102      get { return PopulationSizeParameter.Value; }
103      set { PopulationSizeParameter.Value = value; }
104    }
105    public ISelector Selector {
106      get { return SelectorParameter.Value; }
107      set { SelectorParameter.Value = value; }
108    }
109    public PercentValue CrossoverProbability {
110      get { return CrossoverProbabilityParameter.Value; }
111      set { CrossoverProbabilityParameter.Value = value; }
112    }
113    public ICrossover Crossover {
114      get { return CrossoverParameter.Value; }
115      set { CrossoverParameter.Value = value; }
116    }
117    public PercentValue MutationProbability {
118      get { return MutationProbabilityParameter.Value; }
119      set { MutationProbabilityParameter.Value = value; }
120    }
121    public IManipulator Mutator {
122      get { return MutatorParameter.Value; }
123      set { MutatorParameter.Value = value; }
124    }
125    public MultiAnalyzer Analyzer {
126      get { return AnalyzerParameter.Value; }
127      set { AnalyzerParameter.Value = value; }
128    }
129    public IntValue MaximumGenerations {
130      get { return MaximumGenerationsParameter.Value; }
131      set { MaximumGenerationsParameter.Value = value; }
132    }
[4514]133    public IntValue SelectedParents {
134      get { return SelectedParentsParameter.Value; }
135      set { SelectedParentsParameter.Value = value; }
136    }
[4017]137    private RandomCreator RandomCreator {
138      get { return (RandomCreator)OperatorGraph.InitialOperator; }
139    }
140    private SolutionsCreator SolutionsCreator {
141      get { return (SolutionsCreator)RandomCreator.Successor; }
142    }
[4045]143    private RankAndCrowdingSorter RankAndCrowdingSorter {
[5356]144      get { return (RankAndCrowdingSorter)((SubScopesCounter)SolutionsCreator.Successor).Successor; }
[4045]145    }
[4017]146    private NSGA2MainLoop MainLoop {
[5366]147      get { return FindMainLoop(RankAndCrowdingSorter.Successor); }
[4017]148    }
[4012]149    #endregion
150
[4086]151    [Storable]
[5143]152    private RankBasedParetoFrontAnalyzer paretoFrontAnalyzer;
[4086]153
[4012]154    [StorableConstructor]
[4902]155    protected NSGA2(bool deserializing) : base(deserializing) { }
[5356]156    protected NSGA2(NSGA2 original, Cloner cloner)
157      : base(original, cloner) {
[5143]158      paretoFrontAnalyzer = (RankBasedParetoFrontAnalyzer)cloner.Clone(original.paretoFrontAnalyzer);
[4902]159      AttachEventHandlers();
160    }
[4012]161    public NSGA2() {
[4017]162      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
163      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
164      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions.", new IntValue(100)));
165      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
[4045]166      Parameters.Add(new ValueParameter<PercentValue>("CrossoverProbability", "The probability that the crossover operator is applied on two parents.", new PercentValue(0.9)));
[4017]167      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
168      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
169      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
170      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
171      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations which should be processed.", new IntValue(1000)));
[4514]172      Parameters.Add(new ValueParameter<IntValue>("SelectedParents", "Each two parents form a new child, typically this value should be twice the population size, but because the NSGA-II is maximally elitist it can be any multiple of 2 greater than 0.", new IntValue(200)));
[4017]173
174      RandomCreator randomCreator = new RandomCreator();
175      SolutionsCreator solutionsCreator = new SolutionsCreator();
[5356]176      SubScopesCounter subScopesCounter = new SubScopesCounter();
[4045]177      RankAndCrowdingSorter rankAndCrowdingSorter = new RankAndCrowdingSorter();
[5356]178      ResultsCollector resultsCollector = new ResultsCollector();
[4017]179      NSGA2MainLoop mainLoop = new NSGA2MainLoop();
[5356]180
[4017]181      OperatorGraph.InitialOperator = randomCreator;
182
183      randomCreator.RandomParameter.ActualName = "Random";
184      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
185      randomCreator.SeedParameter.Value = null;
186      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
187      randomCreator.SetSeedRandomlyParameter.Value = null;
188      randomCreator.Successor = solutionsCreator;
189
190      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
[5356]191      solutionsCreator.Successor = subScopesCounter;
[4017]192
[5356]193      subScopesCounter.Name = "Initialize EvaluatedSolutions";
194      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
195      subScopesCounter.Successor = rankAndCrowdingSorter;
196
[4045]197      rankAndCrowdingSorter.CrowdingDistanceParameter.ActualName = "CrowdingDistance";
198      rankAndCrowdingSorter.RankParameter.ActualName = "Rank";
[5356]199      rankAndCrowdingSorter.Successor = resultsCollector;
[4045]200
[5356]201      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
202      resultsCollector.ResultsParameter.ActualName = "Results";
203      resultsCollector.Successor = mainLoop;
204
[4045]205      mainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
[4017]206      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
207      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
208      mainLoop.CrossoverProbabilityParameter.ActualName = CrossoverProbabilityParameter.Name;
209      mainLoop.MaximumGenerationsParameter.ActualName = MaximumGenerationsParameter.Name;
210      mainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
211      mainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
212      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
213      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
214      mainLoop.ResultsParameter.ActualName = "Results";
[5356]215      mainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
[4017]216
[4045]217      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is ISingleObjectiveSelector)).OrderBy(x => x.Name))
[4017]218        SelectorParameter.ValidValues.Add(selector);
[4045]219      ISelector tournamentSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("CrowdedTournamentSelector"));
220      if (tournamentSelector != null) SelectorParameter.Value = tournamentSelector;
[4017]221
[4045]222      ParameterizeSelectors();
223
[5143]224      paretoFrontAnalyzer = new RankBasedParetoFrontAnalyzer();
225      paretoFrontAnalyzer.RankParameter.ActualName = "Rank";
226      paretoFrontAnalyzer.RankParameter.Depth = 1;
227      paretoFrontAnalyzer.ResultsParameter.ActualName = "Results";
[4086]228      ParameterizeAnalyzers();
229      UpdateAnalyzers();
230
[4017]231      AttachEventHandlers();
[4012]232    }
233
234    public override IDeepCloneable Clone(Cloner cloner) {
[5356]235      return new NSGA2(this, cloner);
[4012]236    }
[4017]237
238    #region Events
239    protected override void OnProblemChanged() {
[4045]240      ParameterizeStochasticOperator(Problem.SolutionCreator);
241      ParameterizeStochasticOperator(Problem.Evaluator);
242      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
243      ParameterizeSolutionsCreator();
[4067]244      ParameterizeRankAndCrowdingSorter();
[4045]245      ParameterizeMainLoop();
246      ParameterizeSelectors();
247      ParameterizeAnalyzers();
248      ParameterizeIterationBasedOperators();
249      UpdateCrossovers();
250      UpdateMutators();
251      UpdateAnalyzers();
252      Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
[4017]253      base.OnProblemChanged();
254    }
255    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
[4045]256      ParameterizeStochasticOperator(Problem.SolutionCreator);
257      ParameterizeSolutionsCreator();
[4017]258      base.Problem_SolutionCreatorChanged(sender, e);
259    }
260    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
[4045]261      ParameterizeStochasticOperator(Problem.Evaluator);
262      ParameterizeSolutionsCreator();
[4067]263      ParameterizeRankAndCrowdingSorter();
[4045]264      ParameterizeMainLoop();
265      ParameterizeSelectors();
266      ParameterizeAnalyzers();
[4017]267      Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
268      base.Problem_EvaluatorChanged(sender, e);
269    }
270    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
[4045]271      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
272      ParameterizeIterationBasedOperators();
273      UpdateCrossovers();
274      UpdateMutators();
275      UpdateAnalyzers();
[4017]276      base.Problem_OperatorsChanged(sender, e);
277    }
278    protected override void Problem_Reset(object sender, EventArgs e) {
279      base.Problem_Reset(sender, e);
280    }
281    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
282      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
[4045]283      ParameterizeSelectors();
[4017]284    }
285    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
[4045]286      ParameterizeSelectors();
[4017]287    }
288    private void Evaluator_QualitiesParameter_ActualNameChanged(object sender, EventArgs e) {
[4067]289      ParameterizeRankAndCrowdingSorter();
[4045]290      ParameterizeMainLoop();
291      ParameterizeSelectors();
292      ParameterizeAnalyzers();
[4017]293    }
[4514]294    private void SelectedParentsParameter_ValueChanged(object sender, EventArgs e) {
295      SelectedParents.ValueChanged += new EventHandler(SelectedParents_ValueChanged);
296      SelectedParents_ValueChanged(null, EventArgs.Empty);
297    }
298    private void SelectedParents_ValueChanged(object sender, EventArgs e) {
299      if (SelectedParents.Value < 2) SelectedParents.Value = 2;
300      else if (SelectedParents.Value % 2 != 0) {
301        SelectedParents.Value = SelectedParents.Value + 1;
302      }
303    }
[4017]304    #endregion
305
306    #region Helpers
307    [StorableHook(HookType.AfterDeserialization)]
[6228]308    private void AfterDeserialization() {
309      AttachEventHandlers();
310    }
311
[4017]312    private void AttachEventHandlers() {
313      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
314      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
[4514]315      SelectedParentsParameter.ValueChanged += new EventHandler(SelectedParentsParameter_ValueChanged);
316      SelectedParents.ValueChanged += new EventHandler(SelectedParents_ValueChanged);
[4017]317      if (Problem != null) {
318        Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
319      }
320    }
[4045]321    private void ParameterizeSolutionsCreator() {
322      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
323      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
324    }
[4067]325    private void ParameterizeRankAndCrowdingSorter() {
326      RankAndCrowdingSorter.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
327      RankAndCrowdingSorter.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
328    }
[4045]329    private void ParameterizeMainLoop() {
330      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
331      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
332      MainLoop.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
333    }
334    private void ParameterizeStochasticOperator(IOperator op) {
335      if (op is IStochasticOperator)
336        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
337    }
338    private void ParameterizeSelectors() {
339      foreach (ISelector selector in SelectorParameter.ValidValues) {
340        selector.CopySelected = new BoolValue(true);
[4514]341        selector.NumberOfSelectedSubScopesParameter.ActualName = SelectedParentsParameter.Name;
[4045]342        ParameterizeStochasticOperator(selector);
343      }
344      if (Problem != null) {
345        foreach (IMultiObjectiveSelector selector in SelectorParameter.ValidValues.OfType<IMultiObjectiveSelector>()) {
346          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
347          selector.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
348        }
349      }
350    }
351    private void ParameterizeAnalyzers() {
[4086]352      if (Problem != null) {
[5143]353        paretoFrontAnalyzer.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
354        paretoFrontAnalyzer.QualitiesParameter.Depth = 1;
[4086]355      }
[4045]356    }
357    private void ParameterizeIterationBasedOperators() {
358      if (Problem != null) {
359        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
360          op.IterationsParameter.ActualName = "Generations";
361          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
362        }
363      }
364    }
365    private void UpdateCrossovers() {
366      ICrossover oldCrossover = CrossoverParameter.Value;
367      CrossoverParameter.ValidValues.Clear();
368      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
369        CrossoverParameter.ValidValues.Add(crossover);
370      if (oldCrossover != null) {
371        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
372        if (crossover != null) CrossoverParameter.Value = crossover;
373      }
374    }
375    private void UpdateMutators() {
376      IManipulator oldMutator = MutatorParameter.Value;
377      MutatorParameter.ValidValues.Clear();
378      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
379        MutatorParameter.ValidValues.Add(mutator);
380      if (oldMutator != null) {
381        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
382        if (mutator != null) MutatorParameter.Value = mutator;
383      }
384    }
385    private void UpdateAnalyzers() {
386      Analyzer.Operators.Clear();
387      if (Problem != null) {
388        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
389          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
390            param.Depth = 1;
391          Analyzer.Operators.Add(analyzer);
392        }
393      }
[5143]394      Analyzer.Operators.Add(paretoFrontAnalyzer);
[4045]395    }
[5366]396    private NSGA2MainLoop FindMainLoop(IOperator start) {
397      IOperator mainLoop = start;
398      while (mainLoop != null && !(mainLoop is NSGA2MainLoop))
399        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
400      if (mainLoop == null) return null;
401      else return (NSGA2MainLoop)mainLoop;
402    }
[4017]403    #endregion
[4012]404  }
405}
Note: See TracBrowser for help on using the repository browser.