QDpy
Loading...
Searching...
No Matches
_population.py
1# SPDX-License-Identifier: LGPL-3.0-or-later
2"""Internal validation and Pareto selection for bounded population searches."""
3
4from math import isfinite
5from operator import index
6
7import numpy as np
8
9from qdpy.containers.pareto import _crowding_distance
10
11
12def _attempt_budget(budget):
13 budget = index(budget)
14 if budget < 0:
15 raise ValueError("budget must be nonnegative.")
16 return budget
17
18
19def _finite_vector(values, name, size=None):
20 vector = np.asarray(values, dtype=float)
21 if (vector.ndim != 1 or not len(vector) or not np.isfinite(vector).all()
22 or (size is not None and len(vector) != size)):
23 raise ValueError(f"{name} must be a nonempty finite vector of the configured length.")
24 return tuple(map(float, vector))
25
26
27def _mean_dissimilarity(values, distance):
28 """Compute one symmetric distance per unordered pair and average each row."""
29 means = np.zeros(len(values))
30 denominator = max(1, len(values) - 1)
31 for i, left in enumerate(values):
32 for j in range(i):
33 gap = float(distance(left, values[j]))
34 if not isfinite(gap) or gap < 0:
35 raise ValueError("Dissimilarities must be finite and nonnegative.")
36 means[i] += gap / denominator
37 means[j] += gap / denominator
38 return means
39
40
41def _pareto_fronts(scores):
42 """Yield nondominated fronts in dominance order, treating all scores as rewards."""
43 dominates = np.zeros((len(scores), len(scores)), dtype=bool)
44 for i, row in enumerate(scores):
45 dominates[i] = np.all(row >= scores, axis=1) & np.any(row > scores, axis=1)
46 counts = dominates.sum(axis=0)
47 while (front := np.flatnonzero(counts == 0)).size:
48 yield front
49 counts -= dominates[front].sum(axis=0)
50 counts[front] = -1
51
52
53def _nsga_order(scores, capacity, diversity=None):
54 """Return ordered survivor indices and their rank/crowding tournament keys."""
55 survivors, keys = [], []
56 for rank, front in enumerate(_pareto_fronts(scores)):
57 crowding = _crowding_distance(scores[front]) if diversity is None else diversity[front]
58 for slot in np.argsort(-crowding, kind="stable")[:capacity - len(survivors)]:
59 survivors.append(int(front[slot]))
60 keys.append((rank, -crowding[slot]))
61 if len(survivors) == capacity:
62 break
63 return survivors, keys
64
65
66def _tournament(population, keys, rng):
67 first, second = rng.integers(len(population), size=2)
68 return population[second if keys[second] < keys[first] else first]
_mean_dissimilarity(values, distance)
_nsga_order(scores, capacity, diversity=None)