1 package net.bmahe.genetics4j.moo.nsga2.spec;
2
3 import java.util.Comparator;
4 import java.util.Optional;
5 import java.util.function.Function;
6
7 import org.immutables.value.Value;
8
9 import net.bmahe.genetics4j.core.Genotype;
10 import net.bmahe.genetics4j.core.spec.selection.SelectionPolicy;
11 import net.bmahe.genetics4j.moo.FitnessVector;
12 import net.bmahe.genetics4j.moo.ObjectiveDistance;
13
14
15
16
17
18
19
20
21
22 @Value.Immutable
23 public abstract class NSGA2Selection<T extends Comparable<T>> implements SelectionPolicy {
24
25
26
27
28
29
30 @Value.Parameter
31 public abstract int numberObjectives();
32
33
34
35
36
37
38
39
40
41 @Value.Default
42 public Comparator<T> dominance() {
43 return (a, b) -> a.compareTo(b);
44 }
45
46
47
48
49
50
51
52
53 @Value.Default
54 public Optional<Comparator<Genotype>> deduplicate() {
55 return Optional.empty();
56 }
57
58
59
60
61
62
63 @Value.Parameter
64 public abstract Function<Integer, Comparator<T>> objectiveComparator();
65
66
67
68
69
70
71 @Value.Parameter
72 public abstract ObjectiveDistance<T> distance();
73
74 public static class Builder<T extends Comparable<T>> extends ImmutableNSGA2Selection.Builder<T> {
75 }
76
77 public static <U extends Comparable<U>> Builder<U> builder() {
78 return new Builder<U>();
79 }
80
81
82
83
84
85
86
87
88
89
90
91
92 public static <U extends Number & Comparable<U>> NSGA2Selection<FitnessVector<U>>
93 ofFitnessVector(final int numberObjectives, final Comparator<Genotype> deduplicate) {
94
95 final var builder = new Builder<FitnessVector<U>>();
96
97 builder.objectiveComparator((m) -> (a, b) -> Double.compare(a.get(m).doubleValue(), b.get(m).doubleValue()))
98 .distance((a, b, m) -> Math.abs(b.get(m).doubleValue() - a.get(m).doubleValue()))
99 .numberObjectives(numberObjectives)
100 .deduplicate(Optional.ofNullable(deduplicate));
101
102 return builder.build();
103 }
104
105
106
107
108
109
110
111
112
113
114 public static <U extends Number & Comparable<U>> NSGA2Selection<FitnessVector<U>>
115 ofFitnessVector(final int numberObjectives) {
116
117 return ofFitnessVector(numberObjectives, null);
118 }
119 }