1 package net.bmahe.genetics4j.moo.spea2.replacement;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.Comparator;
6 import java.util.HashMap;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.Map.Entry;
10 import java.util.Objects;
11 import java.util.Set;
12 import java.util.TreeSet;
13 import java.util.function.BiFunction;
14 import java.util.stream.Collectors;
15 import java.util.stream.IntStream;
16
17 import org.apache.commons.lang3.Validate;
18 import org.apache.commons.lang3.time.DurationFormatUtils;
19 import org.apache.commons.lang3.tuple.Pair;
20 import org.apache.logging.log4j.LogManager;
21 import org.apache.logging.log4j.Logger;
22
23 import net.bmahe.genetics4j.core.Genotype;
24 import net.bmahe.genetics4j.core.Population;
25 import net.bmahe.genetics4j.core.replacement.ReplacementStrategyImplementor;
26 import net.bmahe.genetics4j.core.spec.AbstractEAConfiguration;
27 import net.bmahe.genetics4j.moo.spea2.spec.replacement.SPEA2Replacement;
28
29 public class SPEA2ReplacementStrategyImplementor<T extends Comparable<T>> implements ReplacementStrategyImplementor<T> {
30 public static final Logger logger = LogManager.getLogger(SPEA2ReplacementStrategyImplementor.class);
31
32 private final SPEA2Replacement<T> spea2Replacement;
33
34 public SPEA2ReplacementStrategyImplementor(final SPEA2Replacement<T> _spea2Replacement) {
35 this.spea2Replacement = _spea2Replacement;
36 }
37
38 protected double[] computeStrength(final Comparator<T> dominance, final Population<T> population) {
39 Objects.requireNonNull(dominance);
40 Objects.requireNonNull(population);
41 Validate.isTrue(population.size() > 0);
42
43 final double[] strengths = new double[population.size()];
44 for (int i = 0; i < population.size(); i++) {
45 final T fitness = population.getFitness(i);
46
47 strengths[i] = SPEA2Utils.strength(dominance, i, fitness, population);
48 }
49
50 return strengths;
51 }
52
53 protected double[][] computeObjectiveDistances(final BiFunction<T, T, Double> distance,
54 final Population<T> population) {
55 Objects.requireNonNull(distance);
56 Objects.requireNonNull(population);
57 Validate.isTrue(population.size() > 0);
58
59 final double[][] distanceObjectives = new double[population.size()][population.size()];
60
61 for (int i = 0; i < population.size(); i++) {
62 for (int j = 0; j < i; j++) {
63 final Double distanceMeasure = distance.apply(population.getFitness(i), population.getFitness(j));
64 distanceObjectives[i][j] = distanceMeasure;
65 distanceObjectives[j][i] = distanceMeasure;
66 }
67
68 distanceObjectives[i][i] = 0.0;
69 }
70 return distanceObjectives;
71 }
72
73 protected double[] computeRawFitness(final Comparator<T> dominance, final double[] strengths,
74 final Population<T> population) {
75 Objects.requireNonNull(dominance);
76 Objects.requireNonNull(strengths);
77 Objects.requireNonNull(population);
78 Validate.isTrue(population.size() == strengths.length);
79 Validate.isTrue(population.size() > 0);
80
81 final double[] rawFitness = new double[population.size()];
82 for (int i = 0; i < population.size(); i++) {
83 final T fitness = population.getFitness(i);
84
85 rawFitness[i] = SPEA2Utils.rawFitness(dominance, strengths, i, fitness, population);
86 }
87
88 return rawFitness;
89 }
90
91 protected List<List<Pair<Integer, Double>>> computeSortedDistances(final double[][] distanceObjectives,
92 final Population<T> population) {
93 Objects.requireNonNull(distanceObjectives);
94 Objects.requireNonNull(population);
95 Validate.isTrue(population.size() == distanceObjectives.length);
96 Validate.isTrue(population.size() > 0);
97
98 final List<List<Pair<Integer, Double>>> distances = new ArrayList<>();
99 for (int i = 0; i < population.size(); i++) {
100 final T fitness = population.getFitness(i);
101
102 final List<Pair<Integer, Double>> kthDistances = SPEA2Utils
103 .kthDistances(distanceObjectives, i, fitness, population);
104 distances.add(kthDistances);
105
106 }
107 return distances;
108 }
109
110 protected double[] computeDensity(final List<List<Pair<Integer, Double>>> distances, final int k,
111 final Population<T> population) {
112 Objects.requireNonNull(distances);
113 Validate.isTrue(population.size() == distances.size());
114 Validate.isTrue(k > 0);
115 Objects.requireNonNull(population);
116 Validate.isTrue(population.size() > 0);
117
118 final double[] density = new double[population.size()];
119 for (int i = 0; i < population.size(); i++) {
120 density[i] = 1.0d / (distances.get(i).get(k).getRight() + 2);
121 }
122
123 return density;
124 }
125
126 protected double[] computeFinalFitness(final double[] rawFitness, final double[] density,
127 final Population<T> population) {
128 Objects.requireNonNull(rawFitness);
129 Objects.requireNonNull(density);
130 Validate.isTrue(rawFitness.length == density.length);
131 Objects.requireNonNull(population);
132 Validate.isTrue(population.size() > 0);
133 Validate.isTrue(population.size() == density.length);
134
135 final double[] finalFitness = new double[population.size()];
136 for (int i = 0; i < population.size(); i++) {
137 finalFitness[i] = rawFitness[i] + density[i];
138 }
139
140 return finalFitness;
141 }
142
143 protected int skipNull(final List<Pair<Integer, Double>> distances, final int i) {
144 Objects.requireNonNull(distances);
145 Validate.isTrue(i >= 0);
146 Validate.isTrue(i <= distances.size());
147
148 int j = i;
149
150 while (j < distances.size() && distances.get(j) == null) {
151 j++;
152 }
153
154 return j;
155 }
156
157 protected List<Integer> computeAdditionalIndividuals(final Set<Integer> selectedIndex, final double[] rawFitness,
158 final Population<T> population, final int numIndividuals) {
159 Objects.requireNonNull(selectedIndex);
160 Objects.requireNonNull(rawFitness);
161 Objects.requireNonNull(population);
162 Validate.isTrue(rawFitness.length == population.size());
163 Validate.isTrue(numIndividuals >= selectedIndex.size());
164
165 if (numIndividuals == selectedIndex.size()) {
166 return Collections.emptyList();
167 }
168
169 return IntStream.range(0, population.size())
170 .boxed()
171 .filter(i -> selectedIndex.contains(i) == false)
172 .sorted((a, b) -> Double.compare(rawFitness[a], rawFitness[b]))
173 .limit(numIndividuals - selectedIndex.size())
174 .collect(Collectors.toList());
175 }
176
177 protected void truncatePopulation(final List<List<Pair<Integer, Double>>> distances, final Population<T> population,
178 final int numIndividuals, final Set<Integer> selectedIndex) {
179
180 final Map<Integer, List<Pair<Integer, Double>>> selectedDistances = new HashMap<>();
181 final Map<Integer, Map<Integer, Integer>> selectedDistancesIndex = new HashMap<>();
182
183
184
185
186
187
188
189
190
191
192 for (final int index : selectedIndex) {
193
194 final List<Pair<Integer, Double>> kthDistances = distances.get(index)
195 .stream()
196 .filter(p -> selectedIndex.contains(p.getLeft()))
197 .collect(Collectors.toList());
198
199 Validate.isTrue(kthDistances.size() == selectedIndex.size());
200 selectedDistances.put(index, kthDistances);
201
202 for (int i = 0; i < kthDistances.size(); i++) {
203 final Pair<Integer, Double> pair = kthDistances.get(i);
204
205 if (selectedDistancesIndex.containsKey(pair.getKey()) == false) {
206 selectedDistancesIndex.put(pair.getKey(), new HashMap<>());
207 }
208
209 selectedDistancesIndex.get(pair.getKey()).put(index, i);
210 }
211 }
212
213 while (selectedIndex.size() > numIndividuals) {
214
215 int minIndex = -1;
216 List<Pair<Integer, Double>> minDistances = null;
217 for (final int candidateIndex : selectedIndex) {
218
219 if (minIndex < 0) {
220 minIndex = candidateIndex;
221 minDistances = selectedDistances.get(candidateIndex);
222 } else {
223 final List<Pair<Integer, Double>> distancesCandidate = selectedDistances.get(candidateIndex);
224 Validate.isTrue(minDistances.size() == distancesCandidate.size());
225
226 int result = 0;
227 int j = skipNull(minDistances, 0);
228 int l = skipNull(distancesCandidate, 0);
229
230 while (result == 0 && j < minDistances.size() && l < distancesCandidate.size()) {
231
232 result = Double.compare(minDistances.get(j).getRight(), distancesCandidate.get(l).getRight());
233
234 j++;
235 j = skipNull(minDistances, j);
236
237 l++;
238 l = skipNull(distancesCandidate, l);
239 }
240
241 if (result > 0) {
242 minIndex = candidateIndex;
243 minDistances = distancesCandidate;
244 }
245 }
246 }
247
248
249
250
251
252 final Map<Integer, Integer> reverseIndex = selectedDistancesIndex.get(minIndex);
253 for (Entry<Integer, Integer> entry : reverseIndex.entrySet()) {
254 final List<Pair<Integer, Double>> distancesToClean = selectedDistances.get(entry.getKey());
255 distancesToClean.set((int) entry.getValue(), null);
256 }
257 for (Map<Integer, Integer> map : selectedDistancesIndex.values()) {
258 map.remove(minIndex);
259 }
260
261 selectedDistancesIndex.remove(minIndex);
262 selectedDistances.remove(minIndex);
263 selectedIndex.remove(minIndex);
264 }
265
266 }
267
268 protected Set<Integer> environmentalSelection(final List<List<Pair<Integer, Double>>> distances,
269 final double[] rawFitness, final double[] finalFitness, final Population<T> population,
270 final int numIndividuals) {
271
272 final Set<Integer> selectedIndex = IntStream.range(0, population.size())
273 .boxed()
274 .filter(i -> finalFitness[i] < 1)
275 .collect(Collectors.toSet());
276
277 logger.trace("Selected index size: {}", selectedIndex.size());
278
279 if (selectedIndex.size() < numIndividuals) {
280
281 final List<Integer> additionalIndividuals = computeAdditionalIndividuals(
282 selectedIndex,
283 rawFitness,
284 population,
285 numIndividuals);
286
287 logger.trace("Adding {} additional individuals", additionalIndividuals.size());
288 selectedIndex.addAll(additionalIndividuals);
289 }
290
291 if (selectedIndex.size() > numIndividuals) {
292 logger.trace("Need to remove {} individuals", selectedIndex.size() - numIndividuals);
293
294 truncatePopulation(distances, population, numIndividuals, selectedIndex);
295 }
296
297 return selectedIndex;
298 }
299
300 @Override
301 public Population<T> select(final AbstractEAConfiguration<T> eaConfiguration, final long generation,
302 final int numIndividuals, final List<Genotype> population, final List<T> populationScores,
303 final List<Genotype> offsprings, final List<T> offspringScores) {
304 Objects.requireNonNull(eaConfiguration);
305 Validate.isTrue(generation >= 0);
306 Validate.isTrue(numIndividuals > 0);
307 Objects.requireNonNull(population);
308 Objects.requireNonNull(populationScores);
309 Validate.isTrue(population.size() == populationScores.size());
310 Objects.requireNonNull(offsprings);
311 Objects.requireNonNull(offspringScores);
312 Validate.isTrue(offsprings.size() == offspringScores.size());
313
314 final long startTimeNanos = System.nanoTime();
315 logger.debug(
316 "Starting with requested {} individuals - {} population - {} offsprings",
317 numIndividuals,
318 population.size(),
319 offsprings.size());
320
321 final Population<T> archive = new Population<>(population, populationScores);
322 final Population<T> offspringPopulation = new Population<>(offsprings, offspringScores);
323
324 final Population<T> combinedPopulation = new Population<>();
325 if (spea2Replacement.deduplicate().isPresent()) {
326 final Comparator<Genotype> individualDeduplicator = spea2Replacement.deduplicate().get();
327 final Set<Genotype> seenGenotype = new TreeSet<>(individualDeduplicator);
328
329 for (int i = 0; i < archive.size(); i++) {
330 final Genotype genotype = archive.getGenotype(i);
331
332 if (seenGenotype.add(genotype)) {
333 final T fitness = archive.getFitness(i);
334 combinedPopulation.add(genotype, fitness);
335 }
336 }
337 final int ingestedFromArchive = combinedPopulation.size();
338 logger.debug(
339 "Ingested {} individuals from the archive out of the {} available",
340 ingestedFromArchive,
341 archive.size());
342
343 for (int i = 0; i < offspringPopulation.size(); i++) {
344 final Genotype genotype = offspringPopulation.getGenotype(i);
345
346 if (seenGenotype.add(genotype)) {
347 final T fitness = offspringPopulation.getFitness(i);
348 combinedPopulation.add(genotype, fitness);
349 }
350 }
351 if (logger.isDebugEnabled()) {
352 logger.debug(
353 "Ingested {} individuals from the offsprings out of the {} available",
354 combinedPopulation.size() - ingestedFromArchive,
355 offspringPopulation.size());
356 }
357
358 } else {
359 combinedPopulation.addAll(archive);
360 combinedPopulation.addAll(offspringPopulation);
361 }
362
363 final Comparator<T> dominance = switch (eaConfiguration.optimization()) {
364 case MAXIMIZE -> spea2Replacement.dominance();
365 case MINIMIZE -> spea2Replacement.dominance().reversed();
366 };
367
368 final int k = spea2Replacement.k().orElseGet(() -> (int) Math.sqrt(combinedPopulation.size()));
369 logger.trace("Using k={}", k);
370 Validate.isTrue(k > 0);
371
372
373 final double[] strengths = computeStrength(dominance, combinedPopulation);
374
375 final double[][] distanceObjectives = computeObjectiveDistances(spea2Replacement.distance(), combinedPopulation);
376
377 final double[] rawFitness = computeRawFitness(dominance, strengths, combinedPopulation);
378
379 final List<List<Pair<Integer, Double>>> distances = computeSortedDistances(
380 distanceObjectives,
381 combinedPopulation);
382
383 final double[] density = computeDensity(distances, k, combinedPopulation);
384
385 final double[] finalFitness = computeFinalFitness(rawFitness, density, combinedPopulation);
386
387
388
389 final Set<Integer> selectedIndex = environmentalSelection(
390 distances,
391 rawFitness,
392 finalFitness,
393 combinedPopulation,
394 numIndividuals);
395
396 final Population<T> newPopulation = new Population<>();
397 for (final int i : selectedIndex) {
398 newPopulation.add(combinedPopulation.getGenotype(i), combinedPopulation.getFitness(i));
399 }
400
401 final long endTimeNanos = System.nanoTime();
402 if (logger.isDebugEnabled()) {
403 logger.debug(
404 "Finished with {} new population - Computation time: {}",
405 newPopulation.size(),
406 DurationFormatUtils.formatDurationHMS((endTimeNanos - startTimeNanos) / 1_000_000));
407 }
408
409 return newPopulation;
410 }
411 }