QDpy
Loading...
Searching...
No Matches
graph_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Evolve portable graph controllers and measure the structure of their active subgraphs."""
7
8import json
9import math
10import operator
11from pathlib import Path
12
13import numpy as np
14
15from qdpy.base import registry
16from qdpy.containers import CVTGrid, Grid
17from .modern import _FixedGeneration, _positive_int
18
19__all__ = ["CartesianGraphSpace", "CartesianGraphPolicy", "GraphMAPElites"]
20
21_VALUE_LIMIT = 1e6
22_PRIMITIVES = {
23 "identity": (1, lambda x: x),
24 "abs": (1, abs),
25 "exp": (1, lambda x: math.exp(min(x, 20.))),
26 "sin": (1, math.sin),
27 "cos": (1, math.cos),
28 "log": (1, lambda x: math.log(max(abs(x), 1e-12))),
29 "sqrt": (1, lambda x: math.sqrt(abs(x))),
30 "tanh": (1, math.tanh),
31 "negative": (1, lambda x: float(x < 0.)),
32 "positive": (1, lambda x: float(x > 0.)),
33 "add": (2, operator.add),
34 "sub": (2, operator.sub),
35 "mul": (2, operator.mul),
36 "div": (2, lambda x, y: x / y if abs(y) > 1e-12 else x),
37 "less": (2, lambda x, y: float(x < y)),
38 "greater": (2, lambda x, y: float(x > y)),
39}
40
41
42
44 """Lay out graph nodes in one sequence, with the last nodes as outputs.
45
46 Every node has an operation gene and two predecessor genes. Operands
47 may refer to observations, constants, or strictly earlier function
48 nodes. Unary functions ignore the second connection. Inactive nodes
49 can still mutate, so later connections can activate new computations.
50
51 :param inputs: Number of observation coordinates.
52 :param outputs: Number of scalar outputs, beginning at the last outputs nodes.
53 :param nodes: Total number of function nodes in the genotype.
54 :param primitives: Ordered built-in operation names. Defaults to all operations.
55 :param constants: Finite scalar terminals available to every node.
56 :param operation_rate: Optional independent mutation rate for operation genes.
57 :param connection_rate: Optional independent mutation rate for operand genes.
58 Unspecified rates default to the inverse genotype length.
59 """
60
61 def __init__(self, inputs, outputs, nodes, *, primitives=None, constants=(.1, 1.),
62 operation_rate=None, connection_rate=None):
63 self.inputs = _positive_int(inputs, "inputs")
64 self.nodes = _positive_int(nodes, "nodes")
65 self.outputs = _positive_int(outputs, "outputs")
66 self.primitives = tuple(_PRIMITIVES if primitives is None else primitives)
67 self.constants = tuple(map(float, constants))
68 if (self.outputs > self.nodes or not self.primitives or len(set(self.primitives)) != len(self.primitives)
69 or any(name not in _PRIMITIVES for name in self.primitives)
70 or any(not math.isfinite(value) or abs(value) > _VALUE_LIMIT for value in self.constants)):
71 raise ValueError("Supply valid counts, distinct built-in operations, and bounded finite constants.")
72 self.dimension = 3 * self.nodes
73 self._terminals = self.inputs + len(self.constants)
74 self._limits = np.asarray([(len(self.primitives), self._terminals + i, self._terminals + i)
75 for i in range(self.nodes)]).ravel()
76 self._arities = tuple(_PRIMITIVES[name][0] for name in self.primitives)
77 self.operation_rate = 1 / self.dimension if operation_rate is None else float(operation_rate)
78 self.connection_rate = 1 / self.dimension if connection_rate is None else float(connection_rate)
79 if not all(0 <= rate <= 1 for rate in (self.operation_rate, self.connection_rate)):
80 raise ValueError("Graph mutation rates must be in [0, 1].")
81 self._rates = np.tile((self.operation_rate, self.connection_rate, self.connection_rate), self.nodes)
82 self._mutable = self._limits > 1
83
84 def _validate(self, genome):
85 values = tuple(map(operator.index, genome))
86 if len(values) != self.dimension or any(not 0 <= gene < hi for gene, hi in zip(values, self._limits)):
87 raise ValueError("Graph genes must select legal operations and earlier predecessors.")
88 return values
89
90
91 def sample(self, rng):
92 """Return a complete immutable integer genotype."""
93 return tuple(map(int, rng.integers(self._limits)))
94
95
96 def mutate(self, genome, rng):
97 """Flip selected genes to a different legal value and retain neutral genes."""
98 values = np.asarray(self._validate(genome))
99 selected = self._mutable & (rng.random(self.dimension) < self._rates)
100 if np.any(selected):
101 new = rng.integers(self._limits[selected] - 1)
102 values[selected] = new + (new >= values[selected])
103 return tuple(map(int, values))
104
105
106 def decode(self, genome):
107 """Return a controller that can be used independently of the search."""
108 return CartesianGraphPolicy(self, genome)
109
110
111
113 """Evaluate an acyclic graph of built-in scalar operations on one observation.
114
115 Inputs and intermediate values are clipped to ±1e6. A protected
116 division returns its numerator at a near-zero denominator.
117 Above-zero, below-zero, and comparison primitives return 0 or 1.
118 Output clipping to the environment's action bounds belongs to the caller.
119
120 :param space: CartesianGraphSpace defining the genotype.
121 :param genome: Flat sequence of validated integer genes.
122 """
123
124 def __init__(self, space, genome):
125 if not isinstance(space, CartesianGraphSpace):
126 raise TypeError("space must be a CartesianGraphSpace.")
127 self.space = space
128 self.genome = space._validate(genome)
129 self._outputs = tuple(range(space._terminals + space.nodes - space.outputs, space._terminals + space.nodes))
130 pending = list(self._outputs)
131 active = {}
132 while pending:
133 node = pending.pop()
134 if node < space._terminals or node in active:
135 continue
136 start = (node - space._terminals) * 3
137 operation = self.genome[start]
138 arity = space._arities[operation]
139 links = self.genome[start + 1:start + 1 + arity]
140 active[node] = (space.primitives[operation], links)
141 pending.extend(links)
142 self.active_nodes = tuple((node, *active[node]) for node in sorted(active))
143 unary = sum(len(links) == 1 for _, _, links in self.active_nodes)
144 self.structure_descriptors = (unary / space.nodes, (len(active) - unary) / space.nodes)
145
146
147 def act(self, observation):
148 """Evaluate each reachable node once so shared operands can be reused."""
149 values = tuple(map(float, observation))
150 if len(values) != self.space.inputs or not all(map(math.isfinite, values)):
151 raise ValueError("Provide one finite value per observation coordinate.")
152 result = dict(enumerate((*map(self._clip, values), *self.space.constants)))
153 for node, name, links in self.active_nodes:
154 result[node] = self._clip(_PRIMITIVES[name][1](*(result[link] for link in links)))
155 return tuple(result[node] for node in self._outputs)
156
157 @staticmethod
158 def _clip(value):
159 return max(-_VALUE_LIMIT, min(_VALUE_LIMIT, value))
160
161
162 def save(self, path):
163 """Save only the genotype, operation names, constants, and graph dimensions."""
164 space = self.space
165 payload = {"format": "qdpy-cartesian-graph-v1", "genome": self.genome, "inputs": space.inputs,
166 "outputs": space.outputs, "nodes": space.nodes, "primitives": space.primitives,
167 "constants": space.constants}
168 Path(path).write_text(json.dumps(payload, allow_nan=False, indent=2) + "\n", encoding="utf-8")
169
170
171 @classmethod
172 def load(cls, path):
173 """Rebuild an inference policy from its versioned JSON representation."""
174 payload = json.loads(Path(path).read_text(encoding="utf-8"))
175 if not isinstance(payload, dict) or payload.pop("format", None) != "qdpy-cartesian-graph-v1":
176 raise ValueError("Unsupported Cartesian graph format.")
177 if set(payload) != {"genome", "inputs", "outputs", "nodes", "primitives", "constants"}:
178 raise ValueError("Invalid Cartesian graph policy fields.")
179 genome = payload.pop("genome")
180 return cls(CartesianGraphSpace(**payload), genome)
181
182
183
184@registry.register
186 """Illuminate behavioral, structural, or joint descriptors using CGP.
187
188 Native evaluators receive an integer genome. Use the space's decode
189 method to obtain a controller, and append structure_descriptors to
190 the behavioral measurements for joint illumination. Each of those
191 two axes reports the fraction of all genotype nodes occupied by
192 active unary or binary functions.
193
194 Feedback is applied in proposal order within each generation.
195 For manual evaluation, use ask_batch() and tell_batch().
196
197 :param container: Best-only Grid or CVTGrid with one objective.
198 :param budget: Candidate evaluation attempts.
199 :param space: CartesianGraphSpace used for initialization and mutation.
200 :param seed: Private initialization and parent selection seed.
201 :param kwargs: Native QDAlgorithm settings, including batch_size.
202 """
203
204 _requires_proposed_genome = True
205
206 def __init__(self, container, budget, space, *, seed=0, **kwargs):
207 if (type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1
208 or container.discard_random_on_bin_overload or len(container.fitness_domain or ()) != 1
209 or not isinstance(space, CartesianGraphSpace)):
210 raise ValueError("Use a best-only scalar Grid or CVTGrid and a CartesianGraphSpace.")
211 for item in container:
212 space._validate(item)
213 self.space, self.seed = space, seed
214 if container.fitness_weights is not None:
215 kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
216 super().__init__(container, _positive_int(budget, "budget"), dimension=space.dimension, **kwargs)
217
218 def reinit(self):
219 """Reset the proposal stream while retaining the archive."""
220 super().reinit()
221 self._rng = np.random.default_rng(self.seed)
222
223 def _internal_ask(self, base_ind):
224 grid = self.container
225 if grid:
226 base_ind[:] = self.space.mutate(grid[self._rng.integers(len(grid))], self._rng)
227 else:
228 base_ind[:] = self.space.sample(self._rng)
229 return base_ind
Executable active graph with structural descriptors and JSON export.
Definition graph_qd.py:112
load(cls, path)
Reload and validate a saved graph without the optimizer.
Definition graph_qd.py:172
save(self, path)
Write an inference policy as versioned JSON.
Definition graph_qd.py:162
act(self, observation)
Return one scalar per output node in output order.
Definition graph_qd.py:147
Define a fixed-length integer genotype for acyclic controller graphs.
Definition graph_qd.py:43
mutate(self, genome, rng)
Mutate operation and connection genes independently within their domains.
Definition graph_qd.py:96
sample(self, rng)
Draw one independent uniform value per legal gene domain.
Definition graph_qd.py:91
decode(self, genome)
Decode the reachable subgraph and its fixed output nodes.
Definition graph_qd.py:106
Run native MAP-Elites with integer-flip mutation of graph controllers.
Definition graph_qd.py:185