Source code for qdpy.algorithms.qd_meta
# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Meta-evolve the feature maps of a population of MAP-Elites searches.
"""Bounded QD-Meta with a shared database of measured base features."""
from collections import deque
from dataclasses import dataclass
from math import isfinite, log
import numpy as np
from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from qdpy.tools import iso_line_dd
from .lm_ma_mae import _LMMAES
from .modern import _positive_int, _variation_settings
__all__ = ["FeatureProjection", "QDMetaResult", "QDMeta"]
## @brief Store an evolved linear map from normalized base features to grid descriptors.
[docs]
@dataclass(frozen=True)
class FeatureProjection:
"""Project bounded features into [0, 1] using signed, L1-normalized rows."""
weights: tuple[tuple[float, ...], ...]
base_domain: tuple[tuple[float, float], ...]
def __post_init__(self):
domain, weights = np.asarray(self.base_domain, dtype=float), np.asarray(self.weights, dtype=float)
if (domain.ndim != 2 or domain.shape[1] != 2 or not len(domain) or weights.ndim != 2 or not len(weights)
or weights.shape[1] != len(domain) or not np.isfinite(domain).all()
or not np.isfinite(weights).all()):
raise ValueError("Supply a finite weight matrix and two bounds per base feature.")
widths = domain[:, 1] - domain[:, 0]
if not np.isfinite(widths).all() or np.any(widths <= 0):
raise ValueError("Base feature intervals must have positive finite spans.")
scale = np.abs(weights).max(axis=1, keepdims=True)
scaled = np.divide(weights, scale, out=np.zeros_like(weights), where=scale > 0)
total = np.abs(scaled).sum(axis=1, keepdims=True)
normalized = np.divide(scaled, total, out=scaled, where=total > 0)
object.__setattr__(self, "weights", tuple(tuple(map(float, row)) for row in normalized))
object.__setattr__(self, "base_domain", tuple(tuple(map(float, row)) for row in domain))
[docs]
def __call__(self, features):
"""Map one vector or a matrix of rows into the learned descriptor space."""
values = np.asarray(features, dtype=float)
lower, upper = np.asarray(self.base_domain).T
if (values.ndim not in (1, 2) or values.shape[-1] != len(lower) or not np.isfinite(values).all()
or np.any((values < lower) | (values > upper))):
raise ValueError("Base features must be finite and within base_domain.")
normalized = (values - lower) / (upper - lower) - .5
return (normalized @ np.asarray(self.weights).T + .5).clip(0., 1.)
## @brief Return a measured repertoire, its feature map, and cumulative budget accounting.
[docs]
@dataclass(frozen=True)
class QDMetaResult:
"""Describe the best archive by meta-fitness. An unsuccessful search has no archive."""
projection: FeatureProjection | None
archive: Grid | None
meta_fitness: float | None
evaluations: int
meta_evaluations: int
generations: int
database_size: int
@dataclass(frozen=True)
class _Measurement:
genome: tuple
fitness: float
base: tuple
## @brief Optimize a feature map with an outer ES and a population of inner MAP-Elites runs.
[docs]
class QDMeta:
"""QD Meta-Evolution following Bossens and Tarapore.
Each generation samples a population of linear feature maps. It
rebuilds a best-only grid for each map from the same shared database
snapshot and runs a fixed number of MAP-Elites proposals. Newly
evaluated genomes join the database for the next generation. Meta
fitness ranks the maps for a limited-memory evolution strategy.
:param dimension: Length of the real-valued genome.
:param base_domain: Finite bounds for each measured base feature.
:param shape: Target grid shape, with one output of the projection per axis.
:param ind_domain: Common lower and upper genome bounds.
:param maximize: Whether greater inner fitness should be retained.
:param initial_samples: Number of real evaluations for initial shared records.
:param inner_evaluations: Number of fresh attempts per projection and generation.
:param population_size: Number of feature maps per outer generation.
:param database_capacity: Capacity of the shared FIFO measurement database.
:param sigma0: Initial step size for the outer limited-memory ES.
:param iso_sigma: Inner isotropic mutation scale.
:param line_sigma: Inner directional mutation scale.
:param seed: Seed for the database initialization, inner searches and outer ES.
"""
def __init__(self, dimension, base_domain, shape, *, ind_domain=(0., 1.), maximize=True,
initial_samples=32, inner_evaluations=16, population_size=6, database_capacity=4096,
sigma0=.45, iso_sigma=.05, line_sigma=.2, seed=0):
self.dimension = _positive_int(dimension, "dimension")
self.shape = tuple(_positive_int(bins, "bin count") for bins in shape)
if not self.shape:
raise ValueError("Provide at least one target descriptor axis.")
self.base_domain = tuple(tuple(pair) for pair in base_domain)
weights = np.ones((len(self.shape), len(self.base_domain)))
projection = FeatureProjection(weights, self.base_domain)
self.base_domain = projection.base_domain
self._population_size = _positive_int(population_size, "population_size")
if self._population_size < 2 or not 0 < sigma0 < np.inf:
raise ValueError("Use at least two feature maps and a positive finite sigma0.")
self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
if not isfinite(self.ind_domain[1] - self.ind_domain[0]):
raise ValueError("The genome domain must have a finite width.")
self._direction = 1. if maximize else -1.
self._iso_sigma, self._line_sigma = iso_sigma, line_sigma
self._initial = _positive_int(initial_samples, "initial_samples")
self.inner_evaluations = _positive_int(inner_evaluations, "inner_evaluations")
self._database = deque(maxlen=_positive_int(database_capacity, "database_capacity"))
seeds = np.random.SeedSequence(seed).spawn(2)
self._rng, outer_rng = (np.random.default_rng(seed) for seed in seeds)
n = weights.size
center = outer_rng.uniform(-.5, .5, size=n)
self._outer = _LMMAES(center, sigma0, self._population_size, min(n, 4 + int(3 * log(n))),
(-1., 1.), outer_rng)
self._initialized = False
self._evaluations = self._meta_evaluations = self._generations = 0
self._best = None
@property
def result(self):
"""Return the best learned archive and cumulative cost counters."""
projection, grid, quality = (None, None, None) if self._best is None else self._best
return QDMetaResult(projection, grid, quality, self._evaluations, self._meta_evaluations,
self._generations, len(self._database))
def _fresh(self):
return self._rng.uniform(*self.ind_domain, self.dimension)
def _measure(self, evaluate, genome):
genome = tuple(map(float, genome))
self._evaluations += 1
result = evaluate(genome)
if result is None:
return None
fitness, features = result
fitness, base = float(fitness), tuple(map(float, features))
if (not isfinite(fitness) or len(base) != len(self.base_domain)
or not all(isfinite(value) and lo <= value <= hi
for value, (lo, hi) in zip(base, self.base_domain))):
raise ValueError("Return finite scalar fitness and one value inside each base feature interval.")
return _Measurement(genome, fitness, base)
def _offer(self, archive, item, descriptors):
cell = archive.index_grid(descriptors)
entries = archive.solutions[cell]
if not entries or self._direction * item.fitness > self._direction * entries[0].fitness.values[0]:
candidate = Individual(item.genome, fitness=Fitness((item.fitness,), weights=(self._direction,)),
features=Features(descriptors))
candidate.scores["base_features"] = item.base
archive.add(candidate)
def _inner(self, projection, snapshot, evaluate):
archive = Grid(shape=self.shape, max_items_per_bin=1, features_domain=((0., 1.),) * len(self.shape),
fitness_domain=((-np.inf, np.inf),), fitness_weights=(self._direction,))
if snapshot:
existing = projection([item.base for item in snapshot])
for item, descriptor in zip(snapshot, existing):
self._offer(archive, item, descriptor)
new = []
for _ in range(self.inner_evaluations):
if archive:
first, second = (archive[i] for i in self._rng.integers(len(archive), size=2))
genes = iso_line_dd(first, second, bounds=self.ind_domain, rng=self._rng,
iso_sigma=self._iso_sigma, line_sigma=self._line_sigma)
else:
genes = self._fresh()
measured = self._measure(evaluate, genes)
if measured is not None:
new.append(measured)
self._offer(archive, measured, projection(measured.base))
return archive, new
## @brief Spend complete outer generations and return the best measured archive.
[docs]
def run(self, evaluate, meta_fitness, *, generations=1):
"""Run fresh inner searches. Both callbacks may return None for a failed measurement.
evaluate takes a genome and returns (scalar fitness, base_features).
meta_fitness takes a completed Grid and returns a scalar to maximize.
The latter should treat the supplied Grid as read-only. Its own
simulator interactions can be tracked in the callback.
"""
generations = _positive_int(generations, "generations")
if not callable(evaluate) or not callable(meta_fitness):
raise TypeError("evaluate and meta_fitness must be callable.")
if not self._initialized:
for _ in range(self._initial):
measured = self._measure(evaluate, self._fresh())
if measured is not None:
self._database.append(measured)
self._initialized = True
for _ in range(generations):
vectors = self._outer.ask(self._population_size)
snapshot = tuple(self._database)
accepted = []
scores = np.full(len(vectors), -np.inf)
for row, vector in enumerate(vectors):
projection = FeatureProjection(vector.reshape(len(self.shape), -1), self.base_domain)
grid, new = self._inner(projection, snapshot, evaluate)
accepted.extend(new)
if not grid:
continue
self._meta_evaluations += 1
value = meta_fitness(grid)
if value is None:
continue
quality = float(value)
if not isfinite(quality):
raise ValueError("Meta-fitness must be finite.")
scores[row] = quality
if self._best is None or quality > self._best[2]:
self._best = projection, grid, quality
self._database.extend(accepted)
valid = np.flatnonzero(np.isfinite(scores))
self._outer.adapt(vectors, valid[np.argsort(-scores[valid], kind="stable")])
self._generations += 1
return self.result