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 @Value.Immutable
21 public abstract class NSGA2Selection<T extends Comparable<T>> implements SelectionPolicy {
22
23
24
25
26
27
28 @Value.Parameter
29 public abstract int numberObjectives();
30
31
32
33
34
35
36
37 @Value.Default
38 public Comparator<T> dominance() {
39 return (a, b) -> a.compareTo(b);
40 }
41
42
43
44
45
46
47
48 @Value.Default
49 public Optional<Comparator<Genotype>> deduplicate() {
50 return Optional.empty();
51 }
52
53
54
55
56
57
58 @Value.Parameter
59 public abstract Function<Integer, Comparator<T>> objectiveComparator();
60
61
62
63
64
65
66 @Value.Parameter
67 public abstract ObjectiveDistance<T> distance();
68
69 public static class Builder<T extends Comparable<T>> extends ImmutableNSGA2Selection.Builder<T> {
70 }
71
72 public static <U extends Comparable<U>> Builder<U> builder() {
73 return new Builder<U>();
74 }
75
76
77
78
79
80
81
82
83
84 public static <U extends Number & Comparable<U>> NSGA2Selection<FitnessVector<U>> ofFitnessVector(
85 final int numberObjectives, final Comparator<Genotype> deduplicate) {
86
87 final var builder = new Builder<FitnessVector<U>>();
88
89 builder.objectiveComparator((m) -> (a, b) -> Double.compare(a.get(m)
90 .doubleValue(),
91 b.get(m)
92 .doubleValue()))
93 .distance((a, b, m) -> Math.abs(b.get(m)
94 .doubleValue()
95 - a.get(m)
96 .doubleValue()))
97 .numberObjectives(numberObjectives)
98 .deduplicate(Optional.ofNullable(deduplicate));
99
100 return builder.build();
101 }
102
103
104
105
106
107
108
109
110 public static <U extends Number & Comparable<U>> NSGA2Selection<FitnessVector<U>> ofFitnessVector(
111 final int numberObjectives) {
112
113 return ofFitnessVector(numberObjectives, null);
114 }
115 }