01 /*
02 * Java Genetic Algorithm Library (jenetics-5.2.0).
03 * Copyright (c) 2007-2020 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
19 */
20 package io.jenetics.ext.moea;
21
22 import java.util.Comparator;
23 import java.util.function.ToIntFunction;
24
25 import io.jenetics.Optimize;
26 import io.jenetics.internal.util.IntComparator;
27 import io.jenetics.util.Seq;
28
29 /**
30 * Crowded distance comparator.
31 *
32 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
33 * @version 4.1
34 * @since 4.1
35 */
36 final class CrowdedComparator<T> implements IntComparator {
37
38 private final int[] _rank;
39 private final double[] _dist;
40
41 CrowdedComparator(
42 final Seq<? extends T> population,
43 final Optimize opt,
44 final Comparator<? super T> dominance,
45 final ElementComparator<? super T> comparator,
46 final ElementDistance<? super T> distance,
47 final ToIntFunction<? super T> dimension
48 ) {
49 _rank = Pareto.rank(
50 population,
51 opt == Optimize.MAXIMUM ? dominance : dominance.reversed()
52 );
53
54 _dist = Pareto.crowdingDistance(
55 population,
56 opt == Optimize.MAXIMUM ? comparator : comparator.reversed(),
57 distance,
58 dimension
59 );
60 }
61
62 @Override
63 public int compare(final int i, final int j) {
64 final int cmp;
65 if (cco(i, j)) cmp = 1;
66 else if (cco(j, i)) cmp = -1;
67 else cmp = 0;
68
69 return cmp;
70 }
71
72 private boolean cco(final int i, final int j) {
73 return _rank[i] < _rank[j] ||
74 (_rank[i] == _rank[j] && _dist[i] > _dist[j]);
75 }
76
77 }
|