Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4068 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

File size: 16.3 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    [StorableConstructor]
142    public NSGA2(bool deserializing) : base(deserializing) { }
143    public NSGA2() {
144      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
145      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
146      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions.", new IntValue(100)));
147      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
148      Parameters.Add(new ValueParameter<PercentValue>("CrossoverProbability", "The probability that the crossover operator is applied on two parents.", new PercentValue(0.9)));
149      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
150      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
151      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
152      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
153      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations which should be processed.", new IntValue(1000)));
154
155      RandomCreator randomCreator = new RandomCreator();
156      SolutionsCreator solutionsCreator = new SolutionsCreator();
157      RankAndCrowdingSorter rankAndCrowdingSorter = new RankAndCrowdingSorter();
158      NSGA2MainLoop mainLoop = new NSGA2MainLoop();
159      OperatorGraph.InitialOperator = randomCreator;
160
161      randomCreator.RandomParameter.ActualName = "Random";
162      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
163      randomCreator.SeedParameter.Value = null;
164      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
165      randomCreator.SetSeedRandomlyParameter.Value = null;
166      randomCreator.Successor = solutionsCreator;
167
168      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
169      solutionsCreator.Successor = rankAndCrowdingSorter;
170
171      rankAndCrowdingSorter.CrowdingDistanceParameter.ActualName = "CrowdingDistance";
172      rankAndCrowdingSorter.RankParameter.ActualName = "Rank";
173      rankAndCrowdingSorter.Successor = mainLoop;
174
175      mainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
176      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
177      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
178      mainLoop.CrossoverProbabilityParameter.ActualName = CrossoverProbabilityParameter.Name;
179      mainLoop.MaximumGenerationsParameter.ActualName = MaximumGenerationsParameter.Name;
180      mainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
181      mainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
182      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
183      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
184      mainLoop.ResultsParameter.ActualName = "Results";
185
186      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is ISingleObjectiveSelector)).OrderBy(x => x.Name))
187        SelectorParameter.ValidValues.Add(selector);
188      ISelector tournamentSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("CrowdedTournamentSelector"));
189      if (tournamentSelector != null) SelectorParameter.Value = tournamentSelector;
190
191      ParameterizeSelectors();
192
193      AttachEventHandlers();
194    }
195
196    public override IDeepCloneable Clone(Cloner cloner) {
197      NSGA2 clone = (NSGA2)base.Clone(cloner);
198      // TODO: Clone additional fields
199      return clone;
200    }
201
202    #region Events
203    protected override void OnProblemChanged() {
204      ParameterizeStochasticOperator(Problem.SolutionCreator);
205      ParameterizeStochasticOperator(Problem.Evaluator);
206      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
207      ParameterizeSolutionsCreator();
208      ParameterizeRankAndCrowdingSorter();
209      ParameterizeMainLoop();
210      ParameterizeSelectors();
211      ParameterizeAnalyzers();
212      ParameterizeIterationBasedOperators();
213      UpdateCrossovers();
214      UpdateMutators();
215      UpdateAnalyzers();
216      Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
217      base.OnProblemChanged();
218    }
219    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
220      ParameterizeStochasticOperator(Problem.SolutionCreator);
221      ParameterizeSolutionsCreator();
222      base.Problem_SolutionCreatorChanged(sender, e);
223    }
224    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
225      ParameterizeStochasticOperator(Problem.Evaluator);
226      ParameterizeSolutionsCreator();
227      ParameterizeRankAndCrowdingSorter();
228      ParameterizeMainLoop();
229      ParameterizeSelectors();
230      ParameterizeAnalyzers();
231      Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
232      base.Problem_EvaluatorChanged(sender, e);
233    }
234    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
235      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
236      ParameterizeIterationBasedOperators();
237      UpdateCrossovers();
238      UpdateMutators();
239      UpdateAnalyzers();
240      base.Problem_OperatorsChanged(sender, e);
241    }
242    protected override void Problem_Reset(object sender, EventArgs e) {
243      base.Problem_Reset(sender, e);
244    }
245    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
246      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
247      ParameterizeSelectors();
248    }
249    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
250      ParameterizeSelectors();
251    }
252    private void Evaluator_QualitiesParameter_ActualNameChanged(object sender, EventArgs e) {
253      ParameterizeRankAndCrowdingSorter();
254      ParameterizeMainLoop();
255      ParameterizeSelectors();
256      ParameterizeAnalyzers();
257    }
258    #endregion
259
260    #region Helpers
261    [StorableHook(HookType.AfterDeserialization)]
262    private void AttachEventHandlers() {
263      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
264      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
265      if (Problem != null) {
266        Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
267      }
268    }
269    private void ParameterizeSolutionsCreator() {
270      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
271      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
272    }
273    private void ParameterizeRankAndCrowdingSorter() {
274      RankAndCrowdingSorter.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
275      RankAndCrowdingSorter.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
276    }
277    private void ParameterizeMainLoop() {
278      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
279      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
280      MainLoop.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
281    }
282    private void ParameterizeStochasticOperator(IOperator op) {
283      if (op is IStochasticOperator)
284        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
285    }
286    private void ParameterizeSelectors() {
287      foreach (ISelector selector in SelectorParameter.ValidValues) {
288        selector.CopySelected = new BoolValue(true);
289        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * PopulationSizeParameter.Value.Value);
290        ParameterizeStochasticOperator(selector);
291      }
292      if (Problem != null) {
293        foreach (IMultiObjectiveSelector selector in SelectorParameter.ValidValues.OfType<IMultiObjectiveSelector>()) {
294          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
295          selector.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
296        }
297      }
298    }
299    private void ParameterizeAnalyzers() {
300      // TODO: Parameterize Analyzers
301    }
302    private void ParameterizeIterationBasedOperators() {
303      if (Problem != null) {
304        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
305          op.IterationsParameter.ActualName = "Generations";
306          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
307        }
308      }
309    }
310    private void UpdateCrossovers() {
311      ICrossover oldCrossover = CrossoverParameter.Value;
312      CrossoverParameter.ValidValues.Clear();
313      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
314        CrossoverParameter.ValidValues.Add(crossover);
315      if (oldCrossover != null) {
316        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
317        if (crossover != null) CrossoverParameter.Value = crossover;
318      }
319    }
320    private void UpdateMutators() {
321      IManipulator oldMutator = MutatorParameter.Value;
322      MutatorParameter.ValidValues.Clear();
323      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
324        MutatorParameter.ValidValues.Add(mutator);
325      if (oldMutator != null) {
326        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
327        if (mutator != null) MutatorParameter.Value = mutator;
328      }
329    }
330    private void UpdateAnalyzers() {
331      Analyzer.Operators.Clear();
332      if (Problem != null) {
333        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
334          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
335            param.Depth = 1;
336          Analyzer.Operators.Add(analyzer);
337        }
338      }
339    }
340    #endregion
341  }
342}
Note: See TracBrowser for help on using the repository browser.