QDpy
Loading...
Searching...
No Matches
nss.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Rank archive parents by surrounded dominance in descriptor space."""
6
7from itertools import product
8
9import numpy as np
10
11from qdpy.base import registry
12from qdpy.containers import CVTGrid, Grid
13from .modern import _FixedGeneration, _bounds, _positive_int
14
15__all__ = ["nss_fronts", "NSSMAPElites"]
16
17
18
19def nss_fronts(qualities, descriptors):
20 """Rank finite scalar qualities (larger is better) and descriptor rows.
21
22 A candidate is surrounded if, for every sign direction, some
23 strictly fitter candidate weakly improves every signed coordinate
24 and strictly improves at least one. Remove each front before
25 determining the next. The returned ranks follow input order.
26
27 Exact direction enumeration is intended for low-dimensional descriptors.
28 """
29 scores = np.asarray(qualities, dtype=float)
30 features = np.asarray(descriptors, dtype=float)
31 if (features.ndim != 2 or not features.shape[1] or scores.shape != (len(features),)
32 or not np.isfinite(features).all() or not np.isfinite(scores).all()):
33 raise ValueError("Supply finite scalar qualities and a matching descriptor matrix.")
34 ranks = np.zeros(len(features), dtype=np.intp)
35 order = np.argsort(-scores, kind="stable")
36 for position, i in enumerate(order):
37 higher = order[:position]
38 higher = higher[(scores[higher] > scores[i]) & np.any(features[higher] != features[i], axis=1)]
39 if not len(higher):
40 continue
41 points = features[higher]
42 active = np.any(points != features[i], axis=0)
43 le, ge = points[:, active] <= features[i, active], points[:, active] >= features[i, active]
44
45 # The last surviving rank in each direction determines when that
46 # direction first becomes empty during front peeling.
47 earliest_empty = int(ranks[higher].max()) + 1
48 for signs in product((False, True), repeat=int(active.sum())):
49 covers = np.all(np.where(signs, ge, le), axis=1)
50 if not covers.any():
51 earliest_empty = 0
52 break
53 earliest_empty = min(earliest_empty, int(ranks[higher[covers]].max()) + 1)
54 ranks[i] = earliest_empty
55 return ranks
56
57
58
59@registry.register
61 """Run NSS-ME on a one-elite Grid or CVTGrid with one fitness objective.
62
63 Parents come from the highest-ranking fronts of the measured archive.
64 A partial boundary front is sampled uniformly without replacement.
65 If the archive has fewer members than the generation size, select
66 every member and fill the remaining slots from the first front.
67 Offspring use clipped Gaussian mutation and native grid admission.
68 Use ask_batch and tell_batch for manual evaluation.
69 """
70
71 _requires_proposed_genome = True
72
73 def __init__(self, container, budget, dimension, *, batch_size=16, ind_domain=(0., 1.),
74 sigma=.1, seed=None, **kwargs):
75 if (type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1
76 or len(container.fitness_domain) != 1):
77 raise ValueError("NSSMAPElites needs a scalar, one-elite Grid or CVTGrid.")
78 if not 0 <= sigma < np.inf:
79 raise ValueError("sigma must be finite and nonnegative.")
80 self.ind_domain = _bounds(ind_domain)
81 self.sigma = float(sigma)
82 self._rng = np.random.default_rng(seed)
83 self._parents = ()
84 super().__init__(container, _positive_int(budget, "budget"),
85 dimension=_positive_int(dimension, "dimension"),
86 batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
87
88 def _start_fixed_batch(self, size):
89 super()._start_fixed_batch(size)
90 archive = self.container
91 if not len(archive):
92 self._parents = ()
93 return
95 direction = np.sign(self._fitness_weights[0])
96 ranks = nss_fronts([direction * archive.get_ind_fitness(ind).values[0] for ind in archive],
97 [tuple(archive.get_ind_features(ind)) for ind in archive])
98 parents = []
99 for rank in range(int(ranks.max()) + 1):
100 front = np.flatnonzero(ranks == rank)
101 remaining = size - len(parents)
102 parents.extend(self._rng.choice(front, size=min(remaining, len(front)), replace=False))
103 if len(parents) == size:
104 break
105 if len(parents) < size:
106 parents.extend(self._rng.choice(np.flatnonzero(ranks == 0), size=size - len(parents)))
107 self._parents = tuple(tuple(archive[i]) for i in parents)
108
109 def _internal_ask(self, base_ind):
110 if self._parents:
111 parent = self._parents[len(self._issued)]
112 base_ind[:] = np.clip(np.asarray(parent) + self._rng.normal(0., self.sigma, self.dimension),
113 *self.ind_domain)
114 else:
115 base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension)
116 return base_ind
117
118 def _commit_generation(self, evaluated):
119 return {i for i, individual in enumerate(evaluated)
120 if individual is not None and self._offer_to_grid(individual, self.container.index_grid(individual))}
_offer_to_grid(self, individual, cell)
Definition modern.py:228
MAP-Elites with non-surrounded-dominated parent selection.
Definition nss.py:60
_commit_generation(self, evaluated)
Definition nss.py:118
_start_fixed_batch(self, size)
Definition nss.py:88
_internal_ask(self, base_ind)
Definition nss.py:109