# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Linkage trees and budgeted gene-pool optimal mixing for MAP-Elites.
# @see https://groups.csail.mit.edu/EVO-DesignOpt/gecco2011Proceedings/proceedings/p617.pdf
"""Recombine categorical archive members in linked groups of variables."""
from dataclasses import dataclass
from operator import index
import numpy as np
from scipy.cluster.hierarchy import linkage
from scipy.special import entr
from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid
__all__ = ["learn_categorical_linkage", "GOMMAPElites", "GOMSearchStats"]
## @brief Derive a family of categorical variable subsets from a measured sample.
[docs]
def learn_categorical_linkage(genomes):
"""Cluster variables by normalized empirical mutual information.
Return singleton groups and all non-root merges, in tree construction
order. Use at least two encoded genomes. Invariant columns have zero
similarity to other columns. Ties follow SciPy's deterministic linkage.
"""
points = np.asarray(genomes)
if points.ndim != 2 or len(points) < 2 or not points.shape[1] or points.dtype.kind not in "biu":
raise ValueError("Supply two or more equal-length categorical integer rows.")
count, width = points.shape
groups = [(column,) for column in range(width)]
if width == 1:
return tuple(groups)
entropy = [entr(np.unique(column, return_counts=True)[1] / count).sum() for column in points.T]
distances = []
for first in range(width - 1):
for second in range(first + 1, width):
scale = entropy[first] + entropy[second]
if not scale:
distances.append(1.)
continue
joint = np.unique(points[:, [first, second]], axis=0, return_counts=True)[1] / count
mutual = scale - entr(joint).sum()
distances.append(float(np.clip(1. - 2 * mutual / scale, 0., 1.)))
for first, second, _, _ in linkage(distances, method="average")[:-1]:
groups.append(tuple(sorted((*groups[int(first)], *groups[int(second)]))))
return tuple(groups)
## @brief Count random measurements, block probes, and updates to the measured archive.
[docs]
@dataclass(frozen=True)
class GOMSearchStats:
"""Every measured intermediate proposal contributes to evaluations."""
evaluations: int
random_evaluations: int
block_evaluations: int
accepted_blocks: int
linkage_fits: int
archive_updates: int
out_of_domain: int
## @brief Adapt gene-pool optimal mixing to categorical best-only archives.
[docs]
class GOMMAPElites:
"""Search a product of integer categories using measured block recombination.
Groups are inferred from archived genomes. Each mix chooses donors
from a snapshot so admissions during the mix do not change its gene
pool. Offer every measured intermediate to the archive. Continue
mixing from a trial if it preserves or improves the parent's scalar
fitness, using the archive's comparison direction.
:param archive: Empty parentless scalar best-only Grid or CVTGrid.
:param nvec: Number of categories for each variable, starting at zero.
:param initial_samples: Minimum number of initial proposals before mixing.
:param random_injection: Probability of a random instead of a mixing proposal.
:param linkage_period: Minimum number of measurements between linkage fits.
:param learn_linkage: Learn groups or use only singleton groups for a control.
:param seed: Private seed for sampling and selecting genomes.
"""
def __init__(self, archive, nvec, *, initial_samples=16, random_injection=.05,
linkage_period=32, learn_linkage=True, seed=0):
_validate_grid(archive)
nvec = tuple(_positive_int(size, "category count") for size in nvec)
if not nvec or max(nvec) > np.iinfo(np.int64).max:
raise ValueError("Use at least one categorical variable with an int64 category count.")
if not 0. <= random_injection <= 1. or type(learn_linkage) is not bool:
raise ValueError("Use a probability for random_injection and a bool for learn_linkage.")
self.archive, self.nvec, self.seed = archive, nvec, seed
self.initial_samples = _positive_int(initial_samples, "initial_samples")
self.linkage_period = _positive_int(linkage_period, "linkage_period")
self.random_injection, self.learn_linkage = random_injection, learn_linkage
def _seed_genome(self, values):
point = tuple(map(index, values))
if len(point) != len(self.nvec) or not all(0 <= value < n for value, n in zip(point, self.nvec)):
raise ValueError("Seed genomes must use valid categories in every position.")
return point
## @brief Run a new search with exactly budget objective calls.
# @param evaluate Callable mapping a genome tuple to (scalar fitness, descriptors).
# @param budget Number of objective calls, including intermediate block probes.
# @param seed_genomes Optional measured start points charged to the budget.
# @return Counters for measurements, mixing, and archive updates.
[docs]
def run(self, evaluate, budget, *, seed_genomes=()):
"""Fill the supplied empty archive and return its search costs."""
if self.archive or not callable(evaluate):
raise ValueError("Use an empty archive and a callable evaluator.")
budget = _positive_int(budget, "budget")
rng = np.random.default_rng(self.seed)
archive = self.archive
weights = archive.fitness_weights
direction = -1. if weights is None or weights[0] < 0. else 1.
seeds, sentinel = iter(seed_genomes), object()
singles = tuple((column,) for column in range(len(self.nvec)))
groups = singles
calls = random_calls = block_calls = accepted = fits = outside = 0
start_updates = archive.nb_added
last_fit = -self.linkage_period
def measure(genome):
nonlocal calls, outside
calls += 1
fitness, features = evaluate(genome)
result = _measurement(archive, ((fitness,), features), genome)
outside += result[1] is None
_offer(archive, result)
return direction * result[0].fitness.values[0]
def random_point():
return tuple(map(int, rng.integers(self.nvec)))
while calls < budget:
supplied = next(seeds, sentinel)
if supplied is not sentinel or calls < self.initial_samples or len(archive) < 2 or (
rng.random() < self.random_injection):
genome = random_point() if supplied is sentinel else self._seed_genome(supplied)
measure(genome)
random_calls += 1
continue
members = tuple(archive)
donors = np.asarray([tuple(member) for member in members], dtype=np.int64)
if self.learn_linkage and calls - last_fit >= self.linkage_period:
groups = learn_categorical_linkage(donors)
fits += 1
last_fit = calls
parent = int(rng.integers(len(members)))
incumbent = donors[parent]
quality = direction * archive.get_ind_fitness(members[parent]).values[0]
before = calls
for group_id in rng.permutation(len(groups)):
columns = list(groups[int(group_id)])
choices = np.flatnonzero(np.any(donors[:, columns] != incumbent[columns], axis=1))
if not len(choices):
continue
child = incumbent.copy()
child[columns] = donors[int(rng.choice(choices)), columns]
score = measure(tuple(map(int, child)))
block_calls += 1
if score >= quality:
accepted += 1
incumbent, quality = child, score
if calls == budget:
break
if calls == before:
measure(random_point())
random_calls += 1
return GOMSearchStats(calls, random_calls, block_calls, accepted, fits, archive.nb_added - start_updates,
outside)