ParetoFront.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-5.1.0).
003  * Copyright (c) 2007-2019 Franz Wilhelmstötter
004  *
005  * Licensed under the Apache License, Version 2.0 (the "License");
006  * you may not use this file except in compliance with the License.
007  * You may obtain a copy of the License at
008  *
009  *      http://www.apache.org/licenses/LICENSE-2.0
010  *
011  * Unless required by applicable law or agreed to in writing, software
012  * distributed under the License is distributed on an "AS IS" BASIS,
013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014  * See the License for the specific language governing permissions and
015  * limitations under the License.
016  *
017  * Author:
018  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
019  */
020 package io.jenetics.ext.moea;
021 
022 import static java.util.Objects.requireNonNull;
023 import static io.jenetics.internal.util.array.revert;
024 
025 import java.util.AbstractSet;
026 import java.util.ArrayList;
027 import java.util.Collection;
028 import java.util.Comparator;
029 import java.util.Iterator;
030 import java.util.List;
031 import java.util.Objects;
032 import java.util.Set;
033 import java.util.function.BiPredicate;
034 import java.util.function.ToIntFunction;
035 import java.util.stream.Collector;
036 import java.util.stream.Collectors;
037 import java.util.stream.IntStream;
038 
039 import io.jenetics.util.ISeq;
040 import io.jenetics.util.ProxySorter;
041 import io.jenetics.util.Seq;
042 
043 /**
044  * This class only contains non-dominate (Pareto-optimal) elements according to
045  * a given <em>dominance</em> measure. Like a {@link Set}, it only contains no
046  * duplicate entries. Unlike the usual set implementation, the iteration order
047  * is deterministic.
048  <p>
049  * You can create a new {@code ParetoFront} for {@link Vec} objects
050  <pre>{@code
051  * final ParetoFront<Vec<double[]>> front = new ParetoFront<>(Vec::dominance);
052  * front.add(Vec.of(1.0, 2.0));
053  * front.add(Vec.of(1.1, 2.5));
054  * front.add(Vec.of(0.9, 2.1));
055  * front.add(Vec.of(0.0, 2.9));
056  * }</pre>
057  *
058  * or directly for {@code double[]} array objects
059  <pre>{@code
060  * final ParetoFront<double[]> front = new ParetoFront<>(Pareto::dominance);
061  * front.add(new double[]{1.0, 2.0});
062  * front.add(new double[]{1.1, 2.5});
063  * front.add(new double[]{0.9, 2.1});
064  * front.add(new double[]{0.0, 2.9});
065  * }</pre>
066  *
067  * You only have to specify the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency">
068  *     Pareto dominance/efficiency</a> measure.
069  *
070  @see Pareto
071  *
072  * @apiNote
073  * Inserting a new element has a time complexity of {@code O(n)}.
074  *
075  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
076  @version 5.1
077  @since 4.1
078  */
079 public final class ParetoFront<T> extends AbstractSet<T> {
080 
081     private final Comparator<? super T> _dominance;
082     private final BiPredicate<? super T, ? super T> _equals;
083     private final List<T> _population = new ArrayList<>();
084 
085     /**
086      * Create a new {@code ParetoSet} with the given {@code dominance} measure.
087      *
088      @since 5.1
089      *
090      @param dominance the <em>Pareto</em> dominance measure
091      @param equals the equals predicate used for keeping the set distinct
092      @throws NullPointerException if the given {@code dominance} measure is
093      *         {@code null}
094      */
095     public ParetoFront(
096         final Comparator<? super T> dominance,
097         final BiPredicate<? super T, ? super T> equals
098     ) {
099         _dominance = requireNonNull(dominance);
100         _equals = requireNonNull(equals);
101     }
102 
103     /**
104      * Create a new {@code ParetoSet} with the given {@code dominance} measure.
105      *
106      @param dominance the <em>Pareto</em> dominance measure
107      @throws NullPointerException if the given {@code dominance} measure is
108      *         {@code null}
109      */
110     public ParetoFront(final Comparator<? super T> dominance) {
111         this(dominance, Objects::equals);
112     }
113 
114     /**
115      * Inserts an {@code element} to this pareto front.
116      *
117      * @implNote
118      * Inserting a new element has a time complexity of {@code O(n)}, where
119      <em>n</em> is the number of elements of {@code this} pareto-front.
120      *
121      @param element the element to add
122      @return {@code true} if this set did not already contain the specified
123      *         element
124      */
125     @Override
126     public boolean add(final T element) {
127         requireNonNull(element);
128 
129         boolean updated = false;
130         final Iterator<T> iterator = _population.iterator();
131         while (iterator.hasNext()) {
132             final T existing = iterator.next();
133 
134             int cmp = _dominance.compare(element, existing);
135             if (cmp > 0) {
136                 iterator.remove();
137                 updated = true;
138             else if (cmp < || _equals.test(element, existing)) {
139                 return updated;
140             }
141         }
142 
143         _population.add(element);
144         return true;
145     }
146 
147     @Override
148     public boolean addAll(final Collection<? extends T> elements) {
149         final int sum = elements.stream()
150             .mapToInt(e -> add(e0)
151             .sum();
152         return sum > 0;
153     }
154 
155     /**
156      * Add the all {@code elements} to {@code this} pareto-set.
157      *
158      * @apiNote
159      * Merging two pareto fronts has a time complexity of {@code O(n*m)}.
160      *
161      @param elements the elements to add
162      @return {@code this} pareto-set
163      @throws NullPointerException if the given parameter is {@code null}
164      */
165     public ParetoFront<T> merge(final ParetoFront<? extends T> elements) {
166         addAll(elements);
167         return this;
168     }
169 
170     /**
171      * Trims {@code this} pareto front to the given size. The front elements are
172      * sorted according its crowding distance and the elements which have smaller
173      * distance to its neighbors are removed first.
174      *
175      <pre>{@code
176      * final ParetoFront<Vec<double[]>> front = new ParetoFront<>(Vec::dominance);
177      * front.trim(10, Vec::compare, Vec::distance, Vec::length);
178      * }</pre>
179      * The example above reduces the given front to 10 elements.
180      *
181      @param size the number of front elements after the trim. If
182      *        {@code size() <= size}, nothing is trimmed.
183      @param comparator the element comparator used for calculating the
184      *        crowded distance
185      @param distance the element distance measure
186      @param dimension the number of vector elements of {@code T}
187      @return {@code this} trimmed pareto front
188      @throws NullPointerException if one of the objects is {@code null}
189      */
190     public ParetoFront<T> trim(
191         final int size,
192         final ElementComparator<? super T> comparator,
193         final ElementDistance<? super T> distance,
194         final ToIntFunction<? super T> dimension
195     ) {
196         requireNonNull(comparator);
197         requireNonNull(distance);
198         requireNonNull(dimension);
199 
200         if (size() > size) {
201             final double[] distances = Pareto.crowdingDistance(
202                 Seq.viewOf(_population),
203                 comparator,
204                 distance,
205                 dimension
206             );
207             final int[] indexes = ProxySorter.sort(distances);
208             revert(indexes);
209 
210             final List<T> list = IntStream.of(indexes)
211                 .limit(size)
212                 .mapToObj(_population::get)
213                 .collect(Collectors.toList());
214 
215             _population.clear();
216             _population.addAll(list);
217         }
218 
219         return this;
220     }
221 
222     @Override
223     public Iterator<T> iterator() {
224         return _population.iterator();
225     }
226 
227     @Override
228     public int size() {
229         return _population.size();
230     }
231 
232     @Override
233     public boolean isEmpty() {
234         return _population.isEmpty();
235     }
236 
237     /**
238      * Return the elements of {@code this} pareto-front as {@link ISeq}.
239      *
240      @return the elements of {@code this} pareto-front as {@link ISeq}
241      */
242     public ISeq<T> toISeq() {
243         return ISeq.of(_population);
244     }
245 
246     /**
247      * Return a pareto-front collector. The natural order of the elements is
248      * used as pareto-dominance order.
249      *
250      @param <C> the element type
251      @return a new pareto-front collector
252      */
253     public static <C extends Comparable<? super C>>
254     Collector<C, ?, ParetoFront<C>> toParetoFront() {
255         return toParetoFront(Comparator.naturalOrder());
256     }
257 
258     /**
259      * Return a pareto-front collector with the given pareto {@code dominance}
260      * measure.
261      *
262      @param dominance the pareto dominance comparator
263      @param <T> the element type
264      @return a new pareto-front collector
265      @throws NullPointerException if the given {@code dominance} collector is
266      *         {@code null}
267      */
268     public static <T> Collector<T, ?, ParetoFront<T>>
269     toParetoFront(final Comparator<? super T> dominance) {
270         return Collector.of(
271             () -> new ParetoFront<>(dominance),
272             ParetoFront::add,
273             ParetoFront::merge
274         );
275     }
276 
277 }