6"""Select one parent from a matrix of case-wise errors."""
8from collections
import Counter
12__all__ = [
"lexicase_index",
"novelty_case_counts",
"novelty_lexicase_index"]
20def lexicase_index(errors, rng, *, epsilon=0.):
21 """Minimize errors one case at a time among the remaining candidates.
23 Zero tolerance implements exact lexicase. With epsilon="mad", a
24 case's median absolute deviation is computed over the original pool.
25 The best error is recomputed among the survivors for every case.
26 Choose uniformly if several candidates remain after the last case.
28 values = np.asarray(errors, dtype=float)
29 if values.ndim != 2
or not min(values.shape)
or not np.isfinite(values).all():
30 raise ValueError(
"Provide a nonempty finite candidate-by-case error matrix.")
31 if not isinstance(epsilon, str):
32 epsilon = float(epsilon)
33 if not 0 <= epsilon < np.inf:
34 raise ValueError(
"epsilon must be a finite nonnegative tolerance or 'mad'.")
35 elif epsilon !=
"mad":
36 raise ValueError(
"epsilon must be a finite nonnegative tolerance or 'mad'.")
37 return _select_casewise(values, rng, epsilon)
40def _select_casewise(errors, rng, epsilon):
41 survivors = np.arange(len(errors))
42 for case
in rng.permutation(errors.shape[1]):
43 original = errors[:, case]
44 scores = original[survivors]
47 scale = np.abs(original).max()
50 original = original / scale
51 scores = original[survivors]
52 tolerance = np.median(np.abs(original - np.median(original)))
55 with np.errstate(over=
"ignore"):
56 survivors = survivors[scores - scores.min() <= tolerance]
57 if len(survivors) == 1:
58 return int(survivors[0])
59 return int(rng.choice(survivors))
66def novelty_case_counts(outputs, *, history=()):
67 """Count an output's occurrences in the current population and history.
69 Choose hashable labels before calling this function. For continuous
70 outputs, a caller can discretize values to determine what counts as
71 the same behavior. History participates in counts and stays outside
74 current = tuple(tuple(row)
for row
in outputs)
75 if not current
or not current[0]:
76 raise ValueError(
"Provide a nonempty candidate-by-case output matrix.")
77 reference = current + tuple(tuple(row)
for row
in history)
78 if any(len(row) != len(current[0])
for row
in reference):
79 raise ValueError(
"All candidate and history rows need the same cases.")
81 counts = [Counter(column)
for column
in zip(*reference, strict=
True)]
82 return np.asarray([[count[label]
for count, label
in zip(counts, row, strict=
True)]
83 for row
in current], dtype=np.int64)
84 except TypeError
as error:
85 raise TypeError(
"Each output label must be hashable.")
from error
90def novelty_lexicase_index(errors, outputs, rng, *, history=()):
91 """Shuffle original error columns and output counts together as cases."""
92 values = np.asarray(errors, dtype=float)
93 counts = novelty_case_counts(outputs, history=history)
94 if values.shape != counts.shape
or not np.isfinite(values).all():
95 raise ValueError(
"Provide one finite error per candidate and case output.")
96 return _select_casewise(np.concatenate((values, counts), axis=1), rng, 0.)