Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1040

  • Fixed a bug in the clone method
File size: 17.1 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.Linq;
24using HeuristicLab.Analysis;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Optimization;
29using HeuristicLab.Optimization.Operators;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.PluginInfrastructure;
33using HeuristicLab.Random;
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>
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.")]
40  [Creatable("Algorithms")]
41  [StorableClass]
42  public class NSGA2 : EngineAlgorithm {
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
54    private ValueParameter<IntValue> SeedParameter {
55      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
56    }
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    }
84    #endregion
85
86    #region Properties
87    public IntValue Seed {
88      get { return SeedParameter.Value; }
89      set { SeedParameter.Value = value; }
90    }
91    public BoolValue SetSeedRandomly {
92      get { return SetSeedRandomlyParameter.Value; }
93      set { SetSeedRandomlyParameter.Value = value; }
94    }
95    public IntValue PopulationSize {
96      get { return PopulationSizeParameter.Value; }
97      set { PopulationSizeParameter.Value = value; }
98    }
99    public ISelector Selector {
100      get { return SelectorParameter.Value; }
101      set { SelectorParameter.Value = value; }
102    }
103    public PercentValue CrossoverProbability {
104      get { return CrossoverProbabilityParameter.Value; }
105      set { CrossoverProbabilityParameter.Value = value; }
106    }
107    public ICrossover Crossover {
108      get { return CrossoverParameter.Value; }
109      set { CrossoverParameter.Value = value; }
110    }
111    public PercentValue MutationProbability {
112      get { return MutationProbabilityParameter.Value; }
113      set { MutationProbabilityParameter.Value = value; }
114    }
115    public IManipulator Mutator {
116      get { return MutatorParameter.Value; }
117      set { MutatorParameter.Value = value; }
118    }
119    public MultiAnalyzer Analyzer {
120      get { return AnalyzerParameter.Value; }
121      set { AnalyzerParameter.Value = value; }
122    }
123    public IntValue MaximumGenerations {
124      get { return MaximumGenerationsParameter.Value; }
125      set { MaximumGenerationsParameter.Value = value; }
126    }
127    private RandomCreator RandomCreator {
128      get { return (RandomCreator)OperatorGraph.InitialOperator; }
129    }
130    private SolutionsCreator SolutionsCreator {
131      get { return (SolutionsCreator)RandomCreator.Successor; }
132    }
133    private RankAndCrowdingSorter RankAndCrowdingSorter {
134      get { return (RankAndCrowdingSorter)SolutionsCreator.Successor; }
135    }
136    private NSGA2MainLoop MainLoop {
137      get { return (NSGA2MainLoop)RankAndCrowdingSorter.Successor; }
138    }
139    #endregion
140
141    [Storable]
142    private BasicMultiObjectiveQualityAnalyzer basicMOQualityAnalyzer;
143
144    [StorableConstructor]
145    public NSGA2(bool deserializing) : base(deserializing) { }
146    public NSGA2() {
147      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
148      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
149      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions.", new IntValue(100)));
150      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
151      Parameters.Add(new ValueParameter<PercentValue>("CrossoverProbability", "The probability that the crossover operator is applied on two parents.", new PercentValue(0.9)));
152      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
153      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
154      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
155      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
156      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations which should be processed.", new IntValue(1000)));
157
158      RandomCreator randomCreator = new RandomCreator();
159      SolutionsCreator solutionsCreator = new SolutionsCreator();
160      RankAndCrowdingSorter rankAndCrowdingSorter = new RankAndCrowdingSorter();
161      NSGA2MainLoop mainLoop = new NSGA2MainLoop();
162     
163      OperatorGraph.InitialOperator = randomCreator;
164
165      randomCreator.RandomParameter.ActualName = "Random";
166      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
167      randomCreator.SeedParameter.Value = null;
168      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
169      randomCreator.SetSeedRandomlyParameter.Value = null;
170      randomCreator.Successor = solutionsCreator;
171
172      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
173      solutionsCreator.Successor = rankAndCrowdingSorter;
174
175      rankAndCrowdingSorter.CrowdingDistanceParameter.ActualName = "CrowdingDistance";
176      rankAndCrowdingSorter.RankParameter.ActualName = "Rank";
177      rankAndCrowdingSorter.Successor = mainLoop;
178
179      mainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
180      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
181      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
182      mainLoop.CrossoverProbabilityParameter.ActualName = CrossoverProbabilityParameter.Name;
183      mainLoop.MaximumGenerationsParameter.ActualName = MaximumGenerationsParameter.Name;
184      mainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
185      mainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
186      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
187      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
188      mainLoop.ResultsParameter.ActualName = "Results";
189
190      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is ISingleObjectiveSelector)).OrderBy(x => x.Name))
191        SelectorParameter.ValidValues.Add(selector);
192      ISelector tournamentSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("CrowdedTournamentSelector"));
193      if (tournamentSelector != null) SelectorParameter.Value = tournamentSelector;
194
195      ParameterizeSelectors();
196
197      basicMOQualityAnalyzer = new BasicMultiObjectiveQualityAnalyzer();
198      basicMOQualityAnalyzer.RankParameter.ActualName = "Rank";
199      basicMOQualityAnalyzer.RankParameter.Depth = 1;
200      basicMOQualityAnalyzer.ResultsParameter.ActualName = "Results";
201      ParameterizeAnalyzers();
202      UpdateAnalyzers();
203
204      AttachEventHandlers();
205    }
206
207    public override IDeepCloneable Clone(Cloner cloner) {
208      NSGA2 clone = (NSGA2)base.Clone(cloner);
209      clone.basicMOQualityAnalyzer = (BasicMultiObjectiveQualityAnalyzer)cloner.Clone(basicMOQualityAnalyzer);
210      clone.AttachEventHandlers();
211      return clone;
212    }
213
214    #region Events
215    protected override void OnProblemChanged() {
216      ParameterizeStochasticOperator(Problem.SolutionCreator);
217      ParameterizeStochasticOperator(Problem.Evaluator);
218      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
219      ParameterizeSolutionsCreator();
220      ParameterizeRankAndCrowdingSorter();
221      ParameterizeMainLoop();
222      ParameterizeSelectors();
223      ParameterizeAnalyzers();
224      ParameterizeIterationBasedOperators();
225      UpdateCrossovers();
226      UpdateMutators();
227      UpdateAnalyzers();
228      Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
229      base.OnProblemChanged();
230    }
231    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
232      ParameterizeStochasticOperator(Problem.SolutionCreator);
233      ParameterizeSolutionsCreator();
234      base.Problem_SolutionCreatorChanged(sender, e);
235    }
236    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
237      ParameterizeStochasticOperator(Problem.Evaluator);
238      ParameterizeSolutionsCreator();
239      ParameterizeRankAndCrowdingSorter();
240      ParameterizeMainLoop();
241      ParameterizeSelectors();
242      ParameterizeAnalyzers();
243      Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
244      base.Problem_EvaluatorChanged(sender, e);
245    }
246    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
247      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
248      ParameterizeIterationBasedOperators();
249      UpdateCrossovers();
250      UpdateMutators();
251      UpdateAnalyzers();
252      base.Problem_OperatorsChanged(sender, e);
253    }
254    protected override void Problem_Reset(object sender, EventArgs e) {
255      base.Problem_Reset(sender, e);
256    }
257    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
258      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
259      ParameterizeSelectors();
260    }
261    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
262      ParameterizeSelectors();
263    }
264    private void Evaluator_QualitiesParameter_ActualNameChanged(object sender, EventArgs e) {
265      ParameterizeRankAndCrowdingSorter();
266      ParameterizeMainLoop();
267      ParameterizeSelectors();
268      ParameterizeAnalyzers();
269    }
270    #endregion
271
272    #region Helpers
273    [StorableHook(HookType.AfterDeserialization)]
274    private void AttachEventHandlers() {
275      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
276      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
277      if (Problem != null) {
278        Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
279      }
280    }
281    private void ParameterizeSolutionsCreator() {
282      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
283      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
284    }
285    private void ParameterizeRankAndCrowdingSorter() {
286      RankAndCrowdingSorter.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
287      RankAndCrowdingSorter.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
288    }
289    private void ParameterizeMainLoop() {
290      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
291      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
292      MainLoop.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
293    }
294    private void ParameterizeStochasticOperator(IOperator op) {
295      if (op is IStochasticOperator)
296        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
297    }
298    private void ParameterizeSelectors() {
299      foreach (ISelector selector in SelectorParameter.ValidValues) {
300        selector.CopySelected = new BoolValue(true);
301        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * PopulationSizeParameter.Value.Value);
302        ParameterizeStochasticOperator(selector);
303      }
304      if (Problem != null) {
305        foreach (IMultiObjectiveSelector selector in SelectorParameter.ValidValues.OfType<IMultiObjectiveSelector>()) {
306          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
307          selector.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
308        }
309      }
310    }
311    private void ParameterizeAnalyzers() {
312      if (Problem != null) {
313        basicMOQualityAnalyzer.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
314        basicMOQualityAnalyzer.QualitiesParameter.Depth = 1;
315      }
316    }
317    private void ParameterizeIterationBasedOperators() {
318      if (Problem != null) {
319        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
320          op.IterationsParameter.ActualName = "Generations";
321          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
322        }
323      }
324    }
325    private void UpdateCrossovers() {
326      ICrossover oldCrossover = CrossoverParameter.Value;
327      CrossoverParameter.ValidValues.Clear();
328      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
329        CrossoverParameter.ValidValues.Add(crossover);
330      if (oldCrossover != null) {
331        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
332        if (crossover != null) CrossoverParameter.Value = crossover;
333      }
334    }
335    private void UpdateMutators() {
336      IManipulator oldMutator = MutatorParameter.Value;
337      MutatorParameter.ValidValues.Clear();
338      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
339        MutatorParameter.ValidValues.Add(mutator);
340      if (oldMutator != null) {
341        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
342        if (mutator != null) MutatorParameter.Value = mutator;
343      }
344    }
345    private void UpdateAnalyzers() {
346      Analyzer.Operators.Clear();
347      if (Problem != null) {
348        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
349          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
350            param.Depth = 1;
351          Analyzer.Operators.Add(analyzer);
352        }
353      }
354      Analyzer.Operators.Add(basicMOQualityAnalyzer);
355    }
356    #endregion
357  }
358}
Note: See TracBrowser for help on using the repository browser.