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