1 package net.bmahe.genetics4j.moo.spea2.replacement;
2
3 import java.util.Comparator;
4 import java.util.List;
5 import java.util.Objects;
6 import java.util.stream.Collectors;
7 import java.util.stream.IntStream;
8
9 import org.apache.commons.lang3.Validate;
10 import org.apache.commons.lang3.tuple.ImmutablePair;
11 import org.apache.commons.lang3.tuple.Pair;
12
13 import net.bmahe.genetics4j.core.Population;
14
15 public class SPEA2Utils {
16
17 private SPEA2Utils() {
18 }
19
20 public static <T extends Comparable<T>> int strength(final Comparator<T> dominance, final int index, final T fitness,
21 final Population<T> population) {
22 Validate.isTrue(index >= 0);
23 Validate.isTrue(index < population.size());
24
25 Objects.requireNonNull(fitness);
26 Objects.requireNonNull(population);
27 Validate.isTrue(population.size() > 0);
28
29 int dominatedCount = 0;
30
31 for (int j = 0; j < population.size(); j++) {
32 final T fitnessJ = population.getFitness(j);
33
34 if (dominance.compare(fitness, fitnessJ) > 0) {
35 dominatedCount++;
36 }
37 }
38
39 return dominatedCount;
40 }
41
42 public static <T extends Comparable<T>> int rawFitness(final Comparator<T> dominance, final double[] strengths,
43 final int index, final T fitness, final Population<T> population) {
44 Validate.isTrue(index >= 0);
45 Validate.isTrue(index < population.size());
46
47 Objects.requireNonNull(strengths);
48 Objects.requireNonNull(fitness);
49 Objects.requireNonNull(population);
50 Validate.isTrue(population.size() > 0);
51 Validate.isTrue(population.size() == strengths.length);
52
53 int rawFitness = 0;
54
55 for (int j = 0; j < population.size(); j++) {
56 final T fitnessJ = population.getFitness(j);
57
58 if (index != j) {
59 if (dominance.compare(fitness, fitnessJ) < 0) {
60 rawFitness += strengths[j];
61 }
62 }
63 }
64
65 return rawFitness;
66 }
67
68 public static <T extends Comparable<T>> List<Pair<Integer, Double>> kthDistances(final double[][] distanceObjectives,
69 final int index, final T fitness, final Population<T> combinedPopulation) {
70 Objects.requireNonNull(distanceObjectives);
71 Validate.isTrue(index >= 0);
72 Validate.isTrue(index < combinedPopulation.size());
73
74 Objects.requireNonNull(fitness);
75 Objects.requireNonNull(combinedPopulation);
76 Validate.isTrue(combinedPopulation.size() > 0);
77
78 return IntStream.range(0, combinedPopulation.size())
79 .boxed()
80 .sorted((a, b) -> Double.compare(distanceObjectives[index][a], distanceObjectives[index][b]))
81 .map(i -> ImmutablePair.of(i, distanceObjectives[index][i]))
82 .collect(Collectors.toList());
83
84 }
85
86 }