Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ScatterSearch (trunk integration)/HeuristicLab.Algorithms.NSGA2/3.3/NSGA2.cs @ 8086

Last change on this file since 8086 was 8086, checked in by jkarder, 12 years ago

#1331:

  • synced branch with trunk
  • added custom interface (ISimilarityBasedOperator) to mark operators that conduct similarity calculation
  • similarity calculators are now parameterized by the algorithm
  • deleted SolutionPool2TierUpdateMethod
  • deleted KnapsackMultipleGuidesPathRelinker
  • moved IImprovementOperator, IPathRelinker and ISimilarityCalculator to HeuristicLab.Optimization
  • added parameter descriptions
  • fixed plugin references
  • fixed count of EvaluatedSolutions
  • fixed check for duplicate solutions
  • minor code improvements
File size: 19.9 KB
RevLine 
[4012]1#region License Information
2/* HeuristicLab
[7259]3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[4012]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;
[5356]28using HeuristicLab.Operators;
[4012]29using HeuristicLab.Optimization;
[4068]30using HeuristicLab.Optimization.Operators;
[4012]31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[4068]33using HeuristicLab.PluginInfrastructure;
[4017]34using HeuristicLab.Random;
[4012]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>
[4017]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.")]
[4012]41  [Creatable("Algorithms")]
42  [StorableClass]
[5809]43  public class NSGA2 : HeuristicOptimizationEngineAlgorithm, IStorableContent {
[5366]44    public string Filename { get; set; }
45
[4012]46    #region Problem Properties
47    public override Type ProblemType {
[5809]48      get { return typeof(IMultiObjectiveHeuristicOptimizationProblem); }
[4012]49    }
[5809]50    public new IMultiObjectiveHeuristicOptimizationProblem Problem {
51      get { return (IMultiObjectiveHeuristicOptimizationProblem)base.Problem; }
[4012]52      set { base.Problem = value; }
53    }
54    #endregion
55
56    #region Parameter Properties
[4017]57    private ValueParameter<IntValue> SeedParameter {
58      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
[4012]59    }
[4017]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    }
[4514]87    private ValueParameter<IntValue> SelectedParentsParameter {
88      get { return (ValueParameter<IntValue>)Parameters["SelectedParents"]; }
89    }
[4012]90    #endregion
91
92    #region Properties
[4017]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    }
[4514]133    public IntValue SelectedParents {
134      get { return SelectedParentsParameter.Value; }
135      set { SelectedParentsParameter.Value = value; }
136    }
[4017]137    private RandomCreator RandomCreator {
138      get { return (RandomCreator)OperatorGraph.InitialOperator; }
139    }
140    private SolutionsCreator SolutionsCreator {
141      get { return (SolutionsCreator)RandomCreator.Successor; }
142    }
[4045]143    private RankAndCrowdingSorter RankAndCrowdingSorter {
[5356]144      get { return (RankAndCrowdingSorter)((SubScopesCounter)SolutionsCreator.Successor).Successor; }
[4045]145    }
[4017]146    private NSGA2MainLoop MainLoop {
[5366]147      get { return FindMainLoop(RankAndCrowdingSorter.Successor); }
[4017]148    }
[4012]149    #endregion
150
[4086]151    [Storable]
[5143]152    private RankBasedParetoFrontAnalyzer paretoFrontAnalyzer;
[4086]153
[4012]154    [StorableConstructor]
[4902]155    protected NSGA2(bool deserializing) : base(deserializing) { }
[5356]156    protected NSGA2(NSGA2 original, Cloner cloner)
157      : base(original, cloner) {
[5143]158      paretoFrontAnalyzer = (RankBasedParetoFrontAnalyzer)cloner.Clone(original.paretoFrontAnalyzer);
[7351]159      AfterDeserialization();
[4902]160    }
[4012]161    public NSGA2() {
[4017]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."));
[4045]166      Parameters.Add(new ValueParameter<PercentValue>("CrossoverProbability", "The probability that the crossover operator is applied on two parents.", new PercentValue(0.9)));
[4017]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)));
[4514]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)));
[4017]173
174      RandomCreator randomCreator = new RandomCreator();
175      SolutionsCreator solutionsCreator = new SolutionsCreator();
[5356]176      SubScopesCounter subScopesCounter = new SubScopesCounter();
[4045]177      RankAndCrowdingSorter rankAndCrowdingSorter = new RankAndCrowdingSorter();
[5356]178      ResultsCollector resultsCollector = new ResultsCollector();
[4017]179      NSGA2MainLoop mainLoop = new NSGA2MainLoop();
[5356]180
[4017]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;
[5356]191      solutionsCreator.Successor = subScopesCounter;
[4017]192
[5356]193      subScopesCounter.Name = "Initialize EvaluatedSolutions";
194      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
195      subScopesCounter.Successor = rankAndCrowdingSorter;
196
[4045]197      rankAndCrowdingSorter.CrowdingDistanceParameter.ActualName = "CrowdingDistance";
198      rankAndCrowdingSorter.RankParameter.ActualName = "Rank";
[5356]199      rankAndCrowdingSorter.Successor = resultsCollector;
[4045]200
[5356]201      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
202      resultsCollector.ResultsParameter.ActualName = "Results";
203      resultsCollector.Successor = mainLoop;
204
[4045]205      mainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
[4017]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";
[5356]215      mainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
[4017]216
[4045]217      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is ISingleObjectiveSelector)).OrderBy(x => x.Name))
[4017]218        SelectorParameter.ValidValues.Add(selector);
[4045]219      ISelector tournamentSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("CrowdedTournamentSelector"));
220      if (tournamentSelector != null) SelectorParameter.Value = tournamentSelector;
[4017]221
[4045]222      ParameterizeSelectors();
223
[5143]224      paretoFrontAnalyzer = new RankBasedParetoFrontAnalyzer();
225      paretoFrontAnalyzer.RankParameter.ActualName = "Rank";
226      paretoFrontAnalyzer.RankParameter.Depth = 1;
227      paretoFrontAnalyzer.ResultsParameter.ActualName = "Results";
[4086]228      ParameterizeAnalyzers();
229      UpdateAnalyzers();
230
[7351]231      AfterDeserialization();
[4012]232    }
233
234    public override IDeepCloneable Clone(Cloner cloner) {
[5356]235      return new NSGA2(this, cloner);
[4012]236    }
[4017]237
[7209]238    public override void Prepare() {
239      if (Problem != null) base.Prepare();
240    }
241
[4017]242    #region Events
243    protected override void OnProblemChanged() {
[4045]244      ParameterizeStochasticOperator(Problem.SolutionCreator);
245      ParameterizeStochasticOperator(Problem.Evaluator);
[8086]246      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
[4045]247      ParameterizeSolutionsCreator();
[4067]248      ParameterizeRankAndCrowdingSorter();
[4045]249      ParameterizeMainLoop();
250      ParameterizeSelectors();
251      ParameterizeAnalyzers();
252      ParameterizeIterationBasedOperators();
253      UpdateCrossovers();
254      UpdateMutators();
255      UpdateAnalyzers();
256      Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
[4017]257      base.OnProblemChanged();
258    }
259    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
[4045]260      ParameterizeStochasticOperator(Problem.SolutionCreator);
261      ParameterizeSolutionsCreator();
[4017]262      base.Problem_SolutionCreatorChanged(sender, e);
263    }
264    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
[4045]265      ParameterizeStochasticOperator(Problem.Evaluator);
266      ParameterizeSolutionsCreator();
[4067]267      ParameterizeRankAndCrowdingSorter();
[4045]268      ParameterizeMainLoop();
269      ParameterizeSelectors();
270      ParameterizeAnalyzers();
[4017]271      Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
272      base.Problem_EvaluatorChanged(sender, e);
273    }
274    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
[8086]275      foreach (IOperator op in Problem.Operators.OfType<IOperator>()) ParameterizeStochasticOperator(op);
[4045]276      ParameterizeIterationBasedOperators();
277      UpdateCrossovers();
278      UpdateMutators();
279      UpdateAnalyzers();
[4017]280      base.Problem_OperatorsChanged(sender, e);
281    }
282    protected override void Problem_Reset(object sender, EventArgs e) {
283      base.Problem_Reset(sender, e);
284    }
285    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
286      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
[4045]287      ParameterizeSelectors();
[4017]288    }
289    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
[4045]290      ParameterizeSelectors();
[4017]291    }
292    private void Evaluator_QualitiesParameter_ActualNameChanged(object sender, EventArgs e) {
[4067]293      ParameterizeRankAndCrowdingSorter();
[4045]294      ParameterizeMainLoop();
295      ParameterizeSelectors();
296      ParameterizeAnalyzers();
[4017]297    }
[4514]298    private void SelectedParentsParameter_ValueChanged(object sender, EventArgs e) {
299      SelectedParents.ValueChanged += new EventHandler(SelectedParents_ValueChanged);
300      SelectedParents_ValueChanged(null, EventArgs.Empty);
301    }
302    private void SelectedParents_ValueChanged(object sender, EventArgs e) {
303      if (SelectedParents.Value < 2) SelectedParents.Value = 2;
304      else if (SelectedParents.Value % 2 != 0) {
305        SelectedParents.Value = SelectedParents.Value + 1;
306      }
307    }
[4017]308    #endregion
309
310    #region Helpers
311    [StorableHook(HookType.AfterDeserialization)]
[7351]312    private void AfterDeserialization() {
[4017]313      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
314      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
[4514]315      SelectedParentsParameter.ValueChanged += new EventHandler(SelectedParentsParameter_ValueChanged);
316      SelectedParents.ValueChanged += new EventHandler(SelectedParents_ValueChanged);
[4017]317      if (Problem != null) {
318        Problem.Evaluator.QualitiesParameter.ActualNameChanged += new EventHandler(Evaluator_QualitiesParameter_ActualNameChanged);
319      }
320    }
[4045]321    private void ParameterizeSolutionsCreator() {
322      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
323      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
324    }
[4067]325    private void ParameterizeRankAndCrowdingSorter() {
326      RankAndCrowdingSorter.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
327      RankAndCrowdingSorter.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
328    }
[4045]329    private void ParameterizeMainLoop() {
330      MainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
331      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
332      MainLoop.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
333    }
334    private void ParameterizeStochasticOperator(IOperator op) {
335      if (op is IStochasticOperator)
336        ((IStochasticOperator)op).RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
337    }
338    private void ParameterizeSelectors() {
339      foreach (ISelector selector in SelectorParameter.ValidValues) {
340        selector.CopySelected = new BoolValue(true);
[4514]341        selector.NumberOfSelectedSubScopesParameter.ActualName = SelectedParentsParameter.Name;
[4045]342        ParameterizeStochasticOperator(selector);
343      }
344      if (Problem != null) {
345        foreach (IMultiObjectiveSelector selector in SelectorParameter.ValidValues.OfType<IMultiObjectiveSelector>()) {
346          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
347          selector.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
348        }
349      }
350    }
351    private void ParameterizeAnalyzers() {
[4086]352      if (Problem != null) {
[5143]353        paretoFrontAnalyzer.QualitiesParameter.ActualName = Problem.Evaluator.QualitiesParameter.ActualName;
354        paretoFrontAnalyzer.QualitiesParameter.Depth = 1;
[4086]355      }
[4045]356    }
357    private void ParameterizeIterationBasedOperators() {
358      if (Problem != null) {
359        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
360          op.IterationsParameter.ActualName = "Generations";
361          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
362        }
363      }
364    }
365    private void UpdateCrossovers() {
366      ICrossover oldCrossover = CrossoverParameter.Value;
[7511]367      ICrossover defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
[4045]368      CrossoverParameter.ValidValues.Clear();
369      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
370        CrossoverParameter.ValidValues.Add(crossover);
371      if (oldCrossover != null) {
372        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
373        if (crossover != null) CrossoverParameter.Value = crossover;
[7511]374        else oldCrossover = null;
[4045]375      }
[7511]376      if (oldCrossover == null && defaultCrossover != null)
377        CrossoverParameter.Value = defaultCrossover;
[4045]378    }
379    private void UpdateMutators() {
380      IManipulator oldMutator = MutatorParameter.Value;
381      MutatorParameter.ValidValues.Clear();
382      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
383        MutatorParameter.ValidValues.Add(mutator);
384      if (oldMutator != null) {
385        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
386        if (mutator != null) MutatorParameter.Value = mutator;
387      }
388    }
389    private void UpdateAnalyzers() {
390      Analyzer.Operators.Clear();
391      if (Problem != null) {
392        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
393          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
394            param.Depth = 1;
[7172]395          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
[4045]396        }
397      }
[7172]398      Analyzer.Operators.Add(paretoFrontAnalyzer, paretoFrontAnalyzer.EnabledByDefault);
[4045]399    }
[5366]400    private NSGA2MainLoop FindMainLoop(IOperator start) {
401      IOperator mainLoop = start;
402      while (mainLoop != null && !(mainLoop is NSGA2MainLoop))
403        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
404      if (mainLoop == null) return null;
405      else return (NSGA2MainLoop)mainLoop;
406    }
[4017]407    #endregion
[4012]408  }
409}
Note: See TracBrowser for help on using the repository browser.