01 /*
02 * Java Genetic Algorithm Library (jenetics-7.1.1).
03 * Copyright (c) 2007-2022 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.BaseSeq;
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 BaseSeq<? 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
52 ? dominance
53 : dominance.reversed()
54 );
55
56 _dist = Pareto.crowdingDistance(
57 population,
58 opt == Optimize.MAXIMUM
59 ? comparator
60 : comparator.reversed(),
61 distance,
62 dimension
63 );
64 }
65
66 @Override
67 public int compare(final int i, final int j) {
68 if (cco(i, j)) {
69 return 1;
70 } else if (cco(j, i)) {
71 return -1;
72 } else {
73 return 0;
74 }
75 }
76
77 private boolean cco(final int i, final int j) {
78 return _rank[i] < _rank[j] ||
79 (_rank[i] == _rank[j] && _dist[i] > _dist[j]);
80 }
81
82 }
|