Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Algorithms.NSGA2/3.3/NSGA2.cs @ 6646

Last change on this file since 6646 was 5809, checked in by mkommend, 14 years ago

#1418: Reintegrated branch into trunk.

File size: 19.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.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>
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.")]
41  [Creatable("Algorithms")]
42  [StorableClass]
43  public class NSGA2 : HeuristicOptimizationEngineAlgorithm, IStorableContent {
44    public string Filename { get; set; }
45
46    #region Problem Properties
47    public override Type ProblemType {
48      get { return typeof(IMultiObjectiveHeuristicOptimizationProblem); }
49    }
50    public new IMultiObjectiveHeuristicOptimizationProblem Problem {
51      get { return (IMultiObjectiveHeuristicOptimizationProblem)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 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    }
87    private ValueParameter<IntValue> SelectedParentsParameter {
88      get { return (ValueParameter<IntValue>)Parameters["SelectedParents"]; }
89    }
90    #endregion
91
92    #region Properties
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    }
133    public IntValue SelectedParents {
134      get { return SelectedParentsParameter.Value; }
135      set { SelectedParentsParameter.Value = value; }
136    }
137    private RandomCreator RandomCreator {
138      get { return (RandomCreator)OperatorGraph.InitialOperator; }
139    }
140    private SolutionsCreator SolutionsCreator {
141      get { return (SolutionsCreator)RandomCreator.Successor; }
142    }
143    private RankAndCrowdingSorter RankAndCrowdingSorter {
144      get { return (RankAndCrowdingSorter)((SubScopesCounter)SolutionsCreator.Successor).Successor; }
145    }
146    private NSGA2MainLoop MainLoop {
147      get { return FindMainLoop(RankAndCrowdingSorter.Successor); }
148    }
149    #endregion
150
151    [Storable]
152    private RankBasedParetoFrontAnalyzer paretoFrontAnalyzer;
153
154    [StorableConstructor]
155    protected NSGA2(bool deserializing) : base(deserializing) { }
156    protected NSGA2(NSGA2 original, Cloner cloner)
157      : base(original, cloner) {
158      paretoFrontAnalyzer = (RankBasedParetoFrontAnalyzer)cloner.Clone(original.paretoFrontAnalyzer);
159      AttachEventHandlers();
160    }
161    public NSGA2() {
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."));
166      Parameters.Add(new ValueParameter<PercentValue>("CrossoverProbability", "The probability that the crossover operator is applied on two parents.", new PercentValue(0.9)));
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)));
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)));
173
174      RandomCreator randomCreator = new RandomCreator();
175      SolutionsCreator solutionsCreator = new SolutionsCreator();
176      SubScopesCounter subScopesCounter = new SubScopesCounter();
177      RankAndCrowdingSorter rankAndCrowdingSorter = new RankAndCrowdingSorter();
178      ResultsCollector resultsCollector = new ResultsCollector();
179      NSGA2MainLoop mainLoop = new NSGA2MainLoop();
180
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;
191      solutionsCreator.Successor = subScopesCounter;
192
193      subScopesCounter.Name = "Initialize EvaluatedSolutions";
194      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
195      subScopesCounter.Successor = rankAndCrowdingSorter;
196
197      rankAndCrowdingSorter.CrowdingDistanceParameter.ActualName = "CrowdingDistance";
198      rankAndCrowdingSorter.RankParameter.ActualName = "Rank";
199      rankAndCrowdingSorter.Successor = resultsCollector;
200
201      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
202      resultsCollector.ResultsParameter.ActualName = "Results";
203      resultsCollector.Successor = mainLoop;
204
205      mainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
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";
215      mainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
216
217      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is ISingleObjectiveSelector)).OrderBy(x => x.Name))
218        SelectorParameter.ValidValues.Add(selector);
219      ISelector tournamentSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("CrowdedTournamentSelector"));
220      if (tournamentSelector != null) SelectorParameter.Value = tournamentSelector;
221
222      ParameterizeSelectors();
223
224      paretoFrontAnalyzer = new RankBasedParetoFrontAnalyzer();
225      paretoFrontAnalyzer.RankParameter.ActualName = "Rank";
226      paretoFrontAnalyzer.RankParameter.Depth = 1;
227      paretoFrontAnalyzer.ResultsParameter.ActualName = "Results";
228      ParameterizeAnalyzers();
229      UpdateAnalyzers();
230
231      AttachEventHandlers();
232    }
233
234    public override IDeepCloneable Clone(Cloner cloner) {
235      return new NSGA2(this, cloner);
236    }
237
238    #region Events
239    protected override void OnProblemChanged() {
240      ParameterizeStochasticOperator(Problem.SolutionCreator);
241      ParameterizeStochasticOperator(Problem.Evaluator);
242      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
243      ParameterizeSolutionsCreator();
244      ParameterizeRankAndCrowdingSorter();
245      ParameterizeMainLoop();
246      ParameterizeSelectors();
247      ParameterizeAnalyzers();
248      ParameterizeIterationBasedOperators();
249      UpdateCrossovers();
250      UpdateMutators();
251      UpdateAnalyzers();
252      Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
253      base.OnProblemChanged();
254    }
255    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
256      ParameterizeStochasticOperator(Problem.SolutionCreator);
257      ParameterizeSolutionsCreator();
258      base.Problem_SolutionCreatorChanged(sender, e);
259    }
260    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
261      ParameterizeStochasticOperator(Problem.Evaluator);
262      ParameterizeSolutionsCreator();
263      ParameterizeRankAndCrowdingSorter();
264      ParameterizeMainLoop();
265      ParameterizeSelectors();
266      ParameterizeAnalyzers();
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) {
271      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
272      ParameterizeIterationBasedOperators();
273      UpdateCrossovers();
274      UpdateMutators();
275      UpdateAnalyzers();
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);
283      ParameterizeSelectors();
284    }
285    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
286      ParameterizeSelectors();
287    }
288    private void Evaluator_QualitiesParameter_ActualNameChanged(object sender, EventArgs e) {
289      ParameterizeRankAndCrowdingSorter();
290      ParameterizeMainLoop();
291      ParameterizeSelectors();
292      ParameterizeAnalyzers();
293    }
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    }
304    #endregion
305
306    #region Helpers
307    [StorableHook(HookType.AfterDeserialization)]
308    private void AttachEventHandlers() {
309      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
310      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
311      SelectedParentsParameter.ValueChanged += new EventHandler(SelectedParentsParameter_ValueChanged);
312      SelectedParents.ValueChanged += new EventHandler(SelectedParents_ValueChanged);
313      if (Problem != null) {
314        Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
315      }
316    }
317    private void ParameterizeSolutionsCreator() {
318      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
319      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
320    }
321    private void ParameterizeRankAndCrowdingSorter() {
322      RankAndCrowdingSorter.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
323      RankAndCrowdingSorter.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
324    }
325    private void ParameterizeMainLoop() {
326      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
327      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
328      MainLoop.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
329    }
330    private void ParameterizeStochasticOperator(IOperator op) {
331      if (op is IStochasticOperator)
332        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
333    }
334    private void ParameterizeSelectors() {
335      foreach (ISelector selector in SelectorParameter.ValidValues) {
336        selector.CopySelected = new BoolValue(true);
337        selector.NumberOfSelectedSubScopesParameter.ActualName = SelectedParentsParameter.Name;
338        ParameterizeStochasticOperator(selector);
339      }
340      if (Problem != null) {
341        foreach (IMultiObjectiveSelector selector in SelectorParameter.ValidValues.OfType<IMultiObjectiveSelector>()) {
342          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
343          selector.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
344        }
345      }
346    }
347    private void ParameterizeAnalyzers() {
348      if (Problem != null) {
349        paretoFrontAnalyzer.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
350        paretoFrontAnalyzer.QualitiesParameter.Depth = 1;
351      }
352    }
353    private void ParameterizeIterationBasedOperators() {
354      if (Problem != null) {
355        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
356          op.IterationsParameter.ActualName = "Generations";
357          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
358        }
359      }
360    }
361    private void UpdateCrossovers() {
362      ICrossover oldCrossover = CrossoverParameter.Value;
363      CrossoverParameter.ValidValues.Clear();
364      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
365        CrossoverParameter.ValidValues.Add(crossover);
366      if (oldCrossover != null) {
367        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
368        if (crossover != null) CrossoverParameter.Value = crossover;
369      }
370    }
371    private void UpdateMutators() {
372      IManipulator oldMutator = MutatorParameter.Value;
373      MutatorParameter.ValidValues.Clear();
374      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
375        MutatorParameter.ValidValues.Add(mutator);
376      if (oldMutator != null) {
377        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
378        if (mutator != null) MutatorParameter.Value = mutator;
379      }
380    }
381    private void UpdateAnalyzers() {
382      Analyzer.Operators.Clear();
383      if (Problem != null) {
384        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
385          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
386            param.Depth = 1;
387          Analyzer.Operators.Add(analyzer);
388        }
389      }
390      Analyzer.Operators.Add(paretoFrontAnalyzer);
391    }
392    private NSGA2MainLoop FindMainLoop(IOperator start) {
393      IOperator mainLoop = start;
394      while (mainLoop != null && !(mainLoop is NSGA2MainLoop))
395        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
396      if (mainLoop == null) return null;
397      else return (NSGA2MainLoop)mainLoop;
398    }
399    #endregion
400  }
401}
Note: See TracBrowser for help on using the repository browser.