Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1040

  • Added a very very basic analyzer for listing the qualities on the pareto front
File size: 17.0 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      // TODO: Clone additional fields
210      return clone;
211    }
212
213    #region Events
214    protected override void OnProblemChanged() {
215      ParameterizeStochasticOperator(Problem.SolutionCreator);
216      ParameterizeStochasticOperator(Problem.Evaluator);
217      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
218      ParameterizeSolutionsCreator();
219      ParameterizeRankAndCrowdingSorter();
220      ParameterizeMainLoop();
221      ParameterizeSelectors();
222      ParameterizeAnalyzers();
223      ParameterizeIterationBasedOperators();
224      UpdateCrossovers();
225      UpdateMutators();
226      UpdateAnalyzers();
227      Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
228      base.OnProblemChanged();
229    }
230    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
231      ParameterizeStochasticOperator(Problem.SolutionCreator);
232      ParameterizeSolutionsCreator();
233      base.Problem_SolutionCreatorChanged(sender, e);
234    }
235    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
236      ParameterizeStochasticOperator(Problem.Evaluator);
237      ParameterizeSolutionsCreator();
238      ParameterizeRankAndCrowdingSorter();
239      ParameterizeMainLoop();
240      ParameterizeSelectors();
241      ParameterizeAnalyzers();
242      Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
243      base.Problem_EvaluatorChanged(sender, e);
244    }
245    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
246      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
247      ParameterizeIterationBasedOperators();
248      UpdateCrossovers();
249      UpdateMutators();
250      UpdateAnalyzers();
251      base.Problem_OperatorsChanged(sender, e);
252    }
253    protected override void Problem_Reset(object sender, EventArgs e) {
254      base.Problem_Reset(sender, e);
255    }
256    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
257      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
258      ParameterizeSelectors();
259    }
260    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
261      ParameterizeSelectors();
262    }
263    private void Evaluator_QualitiesParameter_ActualNameChanged(object sender, EventArgs e) {
264      ParameterizeRankAndCrowdingSorter();
265      ParameterizeMainLoop();
266      ParameterizeSelectors();
267      ParameterizeAnalyzers();
268    }
269    #endregion
270
271    #region Helpers
272    [StorableHook(HookType.AfterDeserialization)]
273    private void AttachEventHandlers() {
274      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
275      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
276      if (Problem != null) {
277        Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
278      }
279    }
280    private void ParameterizeSolutionsCreator() {
281      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
282      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
283    }
284    private void ParameterizeRankAndCrowdingSorter() {
285      RankAndCrowdingSorter.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
286      RankAndCrowdingSorter.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
287    }
288    private void ParameterizeMainLoop() {
289      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
290      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
291      MainLoop.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
292    }
293    private void ParameterizeStochasticOperator(IOperator op) {
294      if (op is IStochasticOperator)
295        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
296    }
297    private void ParameterizeSelectors() {
298      foreach (ISelector selector in SelectorParameter.ValidValues) {
299        selector.CopySelected = new BoolValue(true);
300        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * PopulationSizeParameter.Value.Value);
301        ParameterizeStochasticOperator(selector);
302      }
303      if (Problem != null) {
304        foreach (IMultiObjectiveSelector selector in SelectorParameter.ValidValues.OfType<IMultiObjectiveSelector>()) {
305          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
306          selector.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
307        }
308      }
309    }
310    private void ParameterizeAnalyzers() {
311      if (Problem != null) {
312        basicMOQualityAnalyzer.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
313        basicMOQualityAnalyzer.QualitiesParameter.Depth = 1;
314      }
315    }
316    private void ParameterizeIterationBasedOperators() {
317      if (Problem != null) {
318        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
319          op.IterationsParameter.ActualName = "Generations";
320          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
321        }
322      }
323    }
324    private void UpdateCrossovers() {
325      ICrossover oldCrossover = CrossoverParameter.Value;
326      CrossoverParameter.ValidValues.Clear();
327      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
328        CrossoverParameter.ValidValues.Add(crossover);
329      if (oldCrossover != null) {
330        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
331        if (crossover != null) CrossoverParameter.Value = crossover;
332      }
333    }
334    private void UpdateMutators() {
335      IManipulator oldMutator = MutatorParameter.Value;
336      MutatorParameter.ValidValues.Clear();
337      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
338        MutatorParameter.ValidValues.Add(mutator);
339      if (oldMutator != null) {
340        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
341        if (mutator != null) MutatorParameter.Value = mutator;
342      }
343    }
344    private void UpdateAnalyzers() {
345      Analyzer.Operators.Clear();
346      if (Problem != null) {
347        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
348          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
349            param.Depth = 1;
350          Analyzer.Operators.Add(analyzer);
351        }
352      }
353      Analyzer.Operators.Add(basicMOQualityAnalyzer);
354    }
355    #endregion
356  }
357}
Note: See TracBrowser for help on using the repository browser.