Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Optimization.Operators/3.3/MultiObjective/FastNonDominatedSort.cs @ 14929

Last change on this file since 14929 was 14929, checked in by gkronber, 7 years ago

#2520 fixed unit tests for new persistence: loading & storing all samples

File size: 8.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Operators;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence;
31
32namespace HeuristicLab.Optimization.Operators {
33  /// <summary>
34  /// FastNonDominatedSort as described in: Deb, Pratap, Agrawal and Meyarivan, "A Fast and Elitist Multiobjective
35  /// Genetic Algorithm: NSGA-II", IEEE Transactions On Evolutionary Computation, Vol. 6, No. 2, April 2002
36  /// </summary>
37  [Item("FastNonDominatedSort", @"FastNonDominatedSort as described in: Deb, Pratap, Agrawal and Meyarivan, ""A Fast and Elitist Multiobjective
38Genetic Algorithm: NSGA-II"", IEEE Transactions On Evolutionary Computation, Vol. 6, No. 2, April 2002")]
39  [StorableType("34f3fc45-3522-4c9c-8166-61551b3776a3")]
40  public class FastNonDominatedSort : SingleSuccessorOperator, IMultiObjectiveOperator {
41    [StorableType("c17e5fac-bca3-4c40-bc99-d9ba2679db22")]
42    private enum DominationResult { Dominates, IsDominated, IsNonDominated };
43
44    #region Parameter properties
45    public IValueLookupParameter<BoolArray> MaximizationParameter {
46      get { return (IValueLookupParameter<BoolArray>)Parameters["Maximization"]; }
47    }
48    public IValueLookupParameter<BoolValue> DominateOnEqualQualitiesParameter {
49      get { return (ValueLookupParameter<BoolValue>)Parameters["DominateOnEqualQualities"]; }
50    }
51    public IScopeTreeLookupParameter<DoubleArray> QualitiesParameter {
52      get { return (IScopeTreeLookupParameter<DoubleArray>)Parameters["Qualities"]; }
53    }
54    public IScopeTreeLookupParameter<IntValue> RankParameter {
55      get { return (IScopeTreeLookupParameter<IntValue>)Parameters["Rank"]; }
56    }
57    #endregion
58
59    [StorableConstructor]
60    protected FastNonDominatedSort(bool deserializing) : base(deserializing) { }
61    protected FastNonDominatedSort(FastNonDominatedSort original, Cloner cloner) : base(original, cloner) { }
62    public FastNonDominatedSort() {
63      Parameters.Add(new ValueLookupParameter<BoolArray>("Maximization", "Whether each objective is maximization or minimization."));
64      Parameters.Add(new ValueLookupParameter<BoolValue>("DominateOnEqualQualities", "Flag which determines wether solutions with equal quality values should be treated as dominated."));
65      Parameters.Add(new ScopeTreeLookupParameter<DoubleArray>("Qualities", "The qualities of a solution.", 1));
66      Parameters.Add(new ScopeTreeLookupParameter<IntValue>("Rank", "The rank of a solution.", 1));
67    }
68
69    public override IOperation Apply() {
70      bool dominateOnEqualQualities = DominateOnEqualQualitiesParameter.ActualValue.Value;
71      bool[] maximization = MaximizationParameter.ActualValue.ToArray();
72      double[][] qualities = QualitiesParameter.ActualValue.Select(x => x.ToArray()).ToArray();
73      if (qualities == null) throw new InvalidOperationException(Name + ": No qualities found.");
74
75      IScope scope = ExecutionContext.Scope;
76      int populationSize = scope.SubScopes.Count;
77
78      List<ScopeList> fronts = new List<ScopeList>();
79      Dictionary<IScope, List<int>> dominatedScopes = new Dictionary<IScope, List<int>>();
80      int[] dominationCounter = new int[populationSize];
81      ItemArray<IntValue> rank = new ItemArray<IntValue>(populationSize);
82
83      for (int pI = 0; pI < populationSize - 1; pI++) {
84        IScope p = scope.SubScopes[pI];
85        List<int> dominatedScopesByp;
86        if (!dominatedScopes.TryGetValue(p, out dominatedScopesByp))
87          dominatedScopes[p] = dominatedScopesByp = new List<int>();
88        for (int qI = pI + 1; qI < populationSize; qI++) {
89          DominationResult test = Dominates(qualities[pI], qualities[qI], maximization, dominateOnEqualQualities);
90          if (test == DominationResult.Dominates) {
91            dominatedScopesByp.Add(qI);
92            dominationCounter[qI] += 1;
93          } else if (test == DominationResult.IsDominated) {
94            dominationCounter[pI] += 1;
95            if (!dominatedScopes.ContainsKey(scope.SubScopes[qI]))
96              dominatedScopes.Add(scope.SubScopes[qI], new List<int>());
97            dominatedScopes[scope.SubScopes[qI]].Add(pI);
98          }
99          if (pI == populationSize - 2
100            && qI == populationSize - 1
101            && dominationCounter[qI] == 0) {
102            rank[qI] = new IntValue(0);
103            AddToFront(scope.SubScopes[qI], fronts, 0);
104          }
105        }
106        if (dominationCounter[pI] == 0) {
107          rank[pI] = new IntValue(0);
108          AddToFront(p, fronts, 0);
109        }
110      }
111      int i = 0;
112      while (i < fronts.Count && fronts[i].Count > 0) {
113        ScopeList nextFront = new ScopeList();
114        foreach (IScope p in fronts[i]) {
115          List<int> dominatedScopesByp;
116          if (dominatedScopes.TryGetValue(p, out dominatedScopesByp)) {
117            for (int k = 0; k < dominatedScopesByp.Count; k++) {
118              int dominatedScope = dominatedScopesByp[k];
119              dominationCounter[dominatedScope] -= 1;
120              if (dominationCounter[dominatedScope] == 0) {
121                rank[dominatedScope] = new IntValue(i + 1);
122                nextFront.Add(scope.SubScopes[dominatedScope]);
123              }
124            }
125          }
126        }
127        i += 1;
128        fronts.Add(nextFront);
129      }
130
131      RankParameter.ActualValue = rank;
132
133      scope.SubScopes.Clear();
134
135      for (i = 0; i < fronts.Count; i++) {
136        Scope frontScope = new Scope("Front " + i);
137        foreach (var p in fronts[i])
138          frontScope.SubScopes.Add(p);
139        if (frontScope.SubScopes.Count > 0)
140          scope.SubScopes.Add(frontScope);
141      }
142      return base.Apply();
143    }
144
145    private static DominationResult Dominates(double[] left, double[] right, bool[] maximizations, bool dominateOnEqualQualities) {
146      //mkommend Caution: do not use LINQ.SequenceEqual for comparing the two quality arrays (left and right) due to performance reasons
147      if (dominateOnEqualQualities) {
148        var equal = true;
149        for (int i = 0; i < left.Length; i++) {
150          if (left[i] != right[i]) {
151            equal = false;
152            break;
153          }
154        }
155        if (equal) return DominationResult.Dominates;
156      }
157
158      bool leftIsBetter = false, rightIsBetter = false;
159      for (int i = 0; i < left.Length; i++) {
160        if (IsDominated(left[i], right[i], maximizations[i])) rightIsBetter = true;
161        else if (IsDominated(right[i], left[i], maximizations[i])) leftIsBetter = true;
162        if (leftIsBetter && rightIsBetter) break;
163      }
164
165      if (leftIsBetter && !rightIsBetter) return DominationResult.Dominates;
166      if (!leftIsBetter && rightIsBetter) return DominationResult.IsDominated;
167      return DominationResult.IsNonDominated;
168    }
169
170    private static bool IsDominated(double left, double right, bool maximization) {
171      return maximization && left < right
172        || !maximization && left > right;
173    }
174
175    private static void AddToFront(IScope p, List<ScopeList> fronts, int i) {
176      if (i == fronts.Count) fronts.Add(new ScopeList());
177      fronts[i].Add(p);
178    }
179
180    public override IDeepCloneable Clone(Cloner cloner) {
181      return new FastNonDominatedSort(this, cloner);
182    }
183
184    [StorableHook(HookType.AfterDeserialization)]
185    private void AfterDeserialization() {
186      // BackwardsCompatibility3.3
187      #region Backwards compatible code, remove with 3.4
188      if (!Parameters.ContainsKey("DominateOnEqualQualities"))
189        Parameters.Add(new ValueLookupParameter<BoolValue>("DominateOnEqualQualities", "Flag which determines wether solutions with equal quality values should be treated as dominated."));
190      #endregion
191    }
192  }
193}
Note: See TracBrowser for help on using the repository browser.