# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Graph Quality-Diversity with feed-forward Cartesian Genetic Programming.
# @see https://doi.org/10.1145/3638529.3653987
"""Evolve portable graph controllers and measure the structure of their active subgraphs."""
import json
import math
import operator
from pathlib import Path
import numpy as np
from qdpy.base import registry
from qdpy.containers import CVTGrid, Grid
from .modern import _FixedGeneration, _positive_int
__all__ = ["CartesianGraphSpace", "CartesianGraphPolicy", "GraphMAPElites"]
_VALUE_LIMIT = 1e6
_PRIMITIVES = {
"identity": (1, lambda x: x),
"abs": (1, abs),
"exp": (1, lambda x: math.exp(min(x, 20.))),
"sin": (1, math.sin),
"cos": (1, math.cos),
"log": (1, lambda x: math.log(max(abs(x), 1e-12))),
"sqrt": (1, lambda x: math.sqrt(abs(x))),
"tanh": (1, math.tanh),
"negative": (1, lambda x: float(x < 0.)),
"positive": (1, lambda x: float(x > 0.)),
"add": (2, operator.add),
"sub": (2, operator.sub),
"mul": (2, operator.mul),
"div": (2, lambda x, y: x / y if abs(y) > 1e-12 else x),
"less": (2, lambda x, y: float(x < y)),
"greater": (2, lambda x, y: float(x > y)),
}
## @brief Define a fixed-length integer genotype for acyclic controller graphs.
[docs]
class CartesianGraphSpace:
"""Lay out graph nodes in one sequence, with the last nodes as outputs.
Every node has an operation gene and two predecessor genes. Operands
may refer to observations, constants, or strictly earlier function
nodes. Unary functions ignore the second connection. Inactive nodes
can still mutate, so later connections can activate new computations.
:param inputs: Number of observation coordinates.
:param outputs: Number of scalar outputs, beginning at the last outputs nodes.
:param nodes: Total number of function nodes in the genotype.
:param primitives: Ordered built-in operation names. Defaults to all operations.
:param constants: Finite scalar terminals available to every node.
:param operation_rate: Optional independent mutation rate for operation genes.
:param connection_rate: Optional independent mutation rate for operand genes.
Unspecified rates default to the inverse genotype length.
"""
def __init__(self, inputs, outputs, nodes, *, primitives=None, constants=(.1, 1.),
operation_rate=None, connection_rate=None):
self.inputs = _positive_int(inputs, "inputs")
self.nodes = _positive_int(nodes, "nodes")
self.outputs = _positive_int(outputs, "outputs")
self.primitives = tuple(_PRIMITIVES if primitives is None else primitives)
self.constants = tuple(map(float, constants))
if (self.outputs > self.nodes or not self.primitives or len(set(self.primitives)) != len(self.primitives)
or any(name not in _PRIMITIVES for name in self.primitives)
or any(not math.isfinite(value) or abs(value) > _VALUE_LIMIT for value in self.constants)):
raise ValueError("Supply valid counts, distinct built-in operations, and bounded finite constants.")
self.dimension = 3 * self.nodes
self._terminals = self.inputs + len(self.constants)
self._limits = np.asarray([(len(self.primitives), self._terminals + i, self._terminals + i)
for i in range(self.nodes)]).ravel()
self._arities = tuple(_PRIMITIVES[name][0] for name in self.primitives)
self.operation_rate = 1 / self.dimension if operation_rate is None else float(operation_rate)
self.connection_rate = 1 / self.dimension if connection_rate is None else float(connection_rate)
if not all(0 <= rate <= 1 for rate in (self.operation_rate, self.connection_rate)):
raise ValueError("Graph mutation rates must be in [0, 1].")
self._rates = np.tile((self.operation_rate, self.connection_rate, self.connection_rate), self.nodes)
self._mutable = self._limits > 1
def _validate(self, genome):
values = tuple(map(operator.index, genome))
if len(values) != self.dimension or any(not 0 <= gene < hi for gene, hi in zip(values, self._limits)):
raise ValueError("Graph genes must select legal operations and earlier predecessors.")
return values
## @brief Draw one independent uniform value per legal gene domain.
[docs]
def sample(self, rng):
"""Return a complete immutable integer genotype."""
return tuple(map(int, rng.integers(self._limits)))
## @brief Mutate operation and connection genes independently within their domains.
[docs]
def mutate(self, genome, rng):
"""Flip selected genes to a different legal value and retain neutral genes."""
values = np.asarray(self._validate(genome))
selected = self._mutable & (rng.random(self.dimension) < self._rates)
if np.any(selected):
new = rng.integers(self._limits[selected] - 1)
values[selected] = new + (new >= values[selected])
return tuple(map(int, values))
## @brief Decode the reachable subgraph and its fixed output nodes.
[docs]
def decode(self, genome):
"""Return a controller that can be used independently of the search."""
return CartesianGraphPolicy(self, genome)
## @brief Executable active graph with structural descriptors and JSON export.
[docs]
class CartesianGraphPolicy:
"""Evaluate an acyclic graph of built-in scalar operations on one observation.
Inputs and intermediate values are clipped to ±1e6. A protected
division returns its numerator at a near-zero denominator.
Above-zero, below-zero, and comparison primitives return 0 or 1.
Output clipping to the environment's action bounds belongs to the caller.
:param space: CartesianGraphSpace defining the genotype.
:param genome: Flat sequence of validated integer genes.
"""
def __init__(self, space, genome):
if not isinstance(space, CartesianGraphSpace):
raise TypeError("space must be a CartesianGraphSpace.")
self.space = space
self.genome = space._validate(genome)
self._outputs = tuple(range(space._terminals + space.nodes - space.outputs, space._terminals + space.nodes))
pending = list(self._outputs)
active = {}
while pending:
node = pending.pop()
if node < space._terminals or node in active:
continue
start = (node - space._terminals) * 3
operation = self.genome[start]
arity = space._arities[operation]
links = self.genome[start + 1:start + 1 + arity]
active[node] = (space.primitives[operation], links)
pending.extend(links)
self.active_nodes = tuple((node, *active[node]) for node in sorted(active))
unary = sum(len(links) == 1 for _, _, links in self.active_nodes)
self.structure_descriptors = (unary / space.nodes, (len(active) - unary) / space.nodes)
## @brief Return one scalar per output node in output order.
[docs]
def act(self, observation):
"""Evaluate each reachable node once so shared operands can be reused."""
values = tuple(map(float, observation))
if len(values) != self.space.inputs or not all(map(math.isfinite, values)):
raise ValueError("Provide one finite value per observation coordinate.")
result = dict(enumerate((*map(self._clip, values), *self.space.constants)))
for node, name, links in self.active_nodes:
result[node] = self._clip(_PRIMITIVES[name][1](*(result[link] for link in links)))
return tuple(result[node] for node in self._outputs)
@staticmethod
def _clip(value):
return max(-_VALUE_LIMIT, min(_VALUE_LIMIT, value))
## @brief Write an inference policy as versioned JSON.
[docs]
def save(self, path):
"""Save only the genotype, operation names, constants, and graph dimensions."""
space = self.space
payload = {"format": "qdpy-cartesian-graph-v1", "genome": self.genome, "inputs": space.inputs,
"outputs": space.outputs, "nodes": space.nodes, "primitives": space.primitives,
"constants": space.constants}
Path(path).write_text(json.dumps(payload, allow_nan=False, indent=2) + "\n", encoding="utf-8")
## @brief Reload and validate a saved graph without the optimizer.
[docs]
@classmethod
def load(cls, path):
"""Rebuild an inference policy from its versioned JSON representation."""
payload = json.loads(Path(path).read_text(encoding="utf-8"))
if not isinstance(payload, dict) or payload.pop("format", None) != "qdpy-cartesian-graph-v1":
raise ValueError("Unsupported Cartesian graph format.")
if set(payload) != {"genome", "inputs", "outputs", "nodes", "primitives", "constants"}:
raise ValueError("Invalid Cartesian graph policy fields.")
genome = payload.pop("genome")
return cls(CartesianGraphSpace(**payload), genome)
## @brief Run native MAP-Elites with integer-flip mutation of graph controllers.
[docs]
@registry.register
class GraphMAPElites(_FixedGeneration):
"""Illuminate behavioral, structural, or joint descriptors using CGP.
Native evaluators receive an integer genome. Use the space's decode
method to obtain a controller, and append structure_descriptors to
the behavioral measurements for joint illumination. Each of those
two axes reports the fraction of all genotype nodes occupied by
active unary or binary functions.
Feedback is applied in proposal order within each generation.
For manual evaluation, use ask_batch() and tell_batch().
:param container: Best-only Grid or CVTGrid with one objective.
:param budget: Candidate evaluation attempts.
:param space: CartesianGraphSpace used for initialization and mutation.
:param seed: Private initialization and parent selection seed.
:param kwargs: Native QDAlgorithm settings, including batch_size.
"""
_requires_proposed_genome = True
def __init__(self, container, budget, space, *, seed=0, **kwargs):
if (type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1
or container.discard_random_on_bin_overload or len(container.fitness_domain or ()) != 1
or not isinstance(space, CartesianGraphSpace)):
raise ValueError("Use a best-only scalar Grid or CVTGrid and a CartesianGraphSpace.")
for item in container:
space._validate(item)
self.space, self.seed = space, seed
if container.fitness_weights is not None:
kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
super().__init__(container, _positive_int(budget, "budget"), dimension=space.dimension, **kwargs)
[docs]
def reinit(self):
"""Reset the proposal stream while retaining the archive."""
super().reinit()
self._rng = np.random.default_rng(self.seed)
def _internal_ask(self, base_ind):
grid = self.container
if grid:
base_ind[:] = self.space.mutate(grid[self._rng.integers(len(grid))], self._rng)
else:
base_ind[:] = self.space.sample(self._rng)
return base_ind