QDpy
Loading...
Searching...
No Matches
reference_niches.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Quality diversity with user-supplied datasets of numeric measures."""
7
8from dataclasses import dataclass
9from math import dist, fsum, isfinite, inf
10
11import numpy as np
12
13from qdpy.containers import CVTGrid
14
15__all__ = ["reference_cvt", "audit_reference_cvt", "ReferenceTarget", "ReferenceAudit"]
16
17
18
24def reference_cvt(targets, *, features_domain=None, fitness_domain=((0., inf),), fitness_weights=(1.,)):
25 """Use raw or embedded examples as nearest-neighbour archive targets.
26
27 Pass the same representation for every reference and candidate. The
28 default descriptor domain is unbounded. Use explicit finite intervals
29 if the search algorithm needs a bounded model, as DMS does. Each input
30 row has a stable zero-based target ID. Deterministic distance ties go to
31 the first matching row.
32 """
33 points = np.asarray(targets, dtype=float)
34 if points.ndim != 2 or min(points.shape) < 1 or not np.isfinite(points).all():
35 raise ValueError("Supply a nonempty matrix of finite target rows.")
36 if len(np.unique(points, axis=0)) != len(points):
37 raise ValueError("Target rows must be distinct.")
38 if features_domain is None:
39 features_domain = ((-inf, inf),) * points.shape[1]
40 else:
41 domain = np.asarray(features_domain, dtype=float)
42 if (domain.shape != (points.shape[1], 2) or np.isnan(domain).any()
43 or np.any(domain[:, 0] > domain[:, 1])):
44 raise ValueError("Use one ordered descriptor interval per target column.")
45 features_domain = tuple(map(tuple, domain))
46 fitness_domain = tuple(tuple(map(float, bounds)) for bounds in fitness_domain)
47 weights = tuple(map(float, fitness_weights))
48 if (len(fitness_domain) != 1 or len(fitness_domain[0]) != 2
49 or not fitness_domain[0][0] <= fitness_domain[0][1]
50 or len(weights) != 1 or not isfinite(weights[0]) or weights[0] == 0):
51 raise ValueError("Provide one ordered fitness interval and one finite, nonzero weight.")
52 return CVTGrid(shape=len(points), centroids=points, features_domain=features_domain,
53 fitness_domain=fitness_domain, fitness_weights=weights)
54
55
56
57@dataclass(frozen=True)
59 """Distance is in the same Euclidean space that defines archive cells."""
60
61 target_id: int
62 fitness: float | None
63 distance: float | None
64
65
66
67@dataclass(frozen=True)
69 """Mean distance uses occupied cells. The coverage denominator is all targets."""
70
71 targets: tuple[ReferenceTarget, ...]
72 occupied: int
73 coverage: float
74 mean_distance: float | None
75 matched_coverage: float | None
76
77
78
82def audit_reference_cvt(archive, *, distance_limit=None):
83 """Read each incumbent's fitness and displacement from its target."""
84 if type(archive) is not CVTGrid or archive.max_items_per_bin != 1 or len(archive.fitness_domain) != 1:
85 raise ValueError("Supply a scalar best-only CVTGrid.")
86 if distance_limit is not None and (not isfinite(distance_limit) or distance_limit < 0):
87 raise ValueError("Use a finite nonnegative distance limit.")
88 rows = []
89 distances = []
90 for target_id, target in enumerate(archive.cluster_centers):
91 members = archive.solutions[(target_id,)]
92 if members:
93 elite = members[0]
94 distance = dist(target, archive.get_ind_features(elite).values)
95 if not isfinite(distance):
96 raise ValueError("Target distance exceeds the representable range.")
97 distances.append(distance)
98 rows.append(ReferenceTarget(target_id, archive.get_ind_fitness(elite).values[0], distance))
99 else:
100 rows.append(ReferenceTarget(target_id, None, None))
101 occupied = len(distances)
102 matched = None if distance_limit is None else sum(d <= distance_limit for d in distances) / len(rows)
103 return ReferenceAudit(tuple(rows), occupied, occupied / len(rows),
104 fsum(d / occupied for d in distances) if occupied else None, matched)
Report occupancy independently of the fraction within a distance limit.
Identify an occupied or empty reference niche and its measured fidelity.