Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.NSGA2/3.3/NSGA2.cs @ 5304

Last change on this file since 5304 was 5143, checked in by abeham, 14 years ago

#1040

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