Source code for qdpy.algorithms.lexicase

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Case-wise parent selection for discrete and continuous errors.
# @see https://arxiv.org/abs/1709.05394

"""Select one parent from a matrix of case-wise errors."""

from collections import Counter

import numpy as np

__all__ = ["lexicase_index", "novelty_case_counts", "novelty_lexicase_index"]


## @brief Select one parent from scores, processing cases in a fresh random order.
# @param errors Finite matrix with candidates as rows and cases as columns.
# @param rng NumPy random generator used for shuffling and tie breaking.
# @param epsilon A nonnegative absolute tolerance, or "mad" for semi-dynamic epsilon-lexicase.
# @return Row index of the selected candidate.
[docs] def lexicase_index(errors, rng, *, epsilon=0.): """Minimize errors one case at a time among the remaining candidates. Zero tolerance implements exact lexicase. With epsilon="mad", a case's median absolute deviation is computed over the original pool. The best error is recomputed among the survivors for every case. Choose uniformly if several candidates remain after the last case. """ values = np.asarray(errors, dtype=float) if values.ndim != 2 or not min(values.shape) or not np.isfinite(values).all(): raise ValueError("Provide a nonempty finite candidate-by-case error matrix.") if not isinstance(epsilon, str): epsilon = float(epsilon) if not 0 <= epsilon < np.inf: raise ValueError("epsilon must be a finite nonnegative tolerance or 'mad'.") elif epsilon != "mad": raise ValueError("epsilon must be a finite nonnegative tolerance or 'mad'.") return _select_casewise(values, rng, epsilon)
def _select_casewise(errors, rng, epsilon): survivors = np.arange(len(errors)) for case in rng.permutation(errors.shape[1]): original = errors[:, case] scores = original[survivors] if epsilon == "mad": # Scale before computing the MAD and differences to avoid overflow. scale = np.abs(original).max() if not scale: continue original = original / scale scores = original[survivors] tolerance = np.median(np.abs(original - np.median(original))) else: tolerance = epsilon with np.errstate(over="ignore"): survivors = survivors[scores - scores.min() <= tolerance] if len(survivors) == 1: return int(survivors[0]) return int(rng.choice(survivors)) ## @brief Count matching outputs independently for each test case. # @param outputs Candidate rows of hashable output labels. # @param history Previously measured output rows with the same case layout. # @return Candidate-by-case matrix of counts, including the current candidate.
[docs] def novelty_case_counts(outputs, *, history=()): """Count an output's occurrences in the current population and history. Choose hashable labels before calling this function. For continuous outputs, a caller can discretize values to determine what counts as the same behavior. History participates in counts and stays outside the selection pool. """ current = tuple(tuple(row) for row in outputs) if not current or not current[0]: raise ValueError("Provide a nonempty candidate-by-case output matrix.") reference = current + tuple(tuple(row) for row in history) if any(len(row) != len(current[0]) for row in reference): raise ValueError("All candidate and history rows need the same cases.") try: counts = [Counter(column) for column in zip(*reference, strict=True)] return np.asarray([[count[label] for count, label in zip(counts, row, strict=True)] for row in current], dtype=np.int64) except TypeError as error: raise TypeError("Each output label must be hashable.") from error
## @brief Select one exact lexicase parent using error and output-rarity cases. # @see https://arxiv.org/abs/1905.09374
[docs] def novelty_lexicase_index(errors, outputs, rng, *, history=()): """Shuffle original error columns and output counts together as cases.""" values = np.asarray(errors, dtype=float) counts = novelty_case_counts(outputs, history=history) if values.shape != counts.shape or not np.isfinite(values).all(): raise ValueError("Provide one finite error per candidate and case output.") return _select_casewise(np.concatenate((values, counts), axis=1), rng, 0.)