44 """Lay out graph nodes in one sequence, with the last nodes as outputs.
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.
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.
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))
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.")
75 for i
in range(self.
nodes)]).ravel()
80 raise ValueError(
"Graph mutation rates must be in [0, 1].")
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.")
92 """Return a complete immutable integer genotype."""
93 return tuple(map(int, rng.integers(self.
_limits)))
97 """Flip selected genes to a different legal value and retain neutral genes."""
98 values = np.asarray(self.
_validate(genome))
101 new = rng.integers(self.
_limits[selected] - 1)
102 values[selected] = new + (new >= values[selected])
103 return tuple(map(int, values))
107 """Return a controller that can be used independently of the search."""
113 """Evaluate an acyclic graph of built-in scalar operations on one observation.
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.
120 :param space: CartesianGraphSpace defining the genotype.
121 :param genome: Flat sequence of validated integer genes.
124 def __init__(self, space, genome):
125 if not isinstance(space, CartesianGraphSpace):
126 raise TypeError(
"space must be a CartesianGraphSpace.")
128 self.
genome = space._validate(genome)
129 self.
_outputs = tuple(range(space._terminals + space.nodes - space.outputs, space._terminals + space.nodes))
134 if node < space._terminals
or node
in active:
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)
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)))
154 result[node] = self.
_clip(_PRIMITIVES[name][1](*(result[link]
for link
in links)))
155 return tuple(result[node]
for node
in self.
_outputs)
159 return max(-_VALUE_LIMIT, min(_VALUE_LIMIT, value))
163 """Save only the genotype, operation names, constants, and graph dimensions."""
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")
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")
186 """Illuminate behavioral, structural, or joint descriptors using CGP.
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.
194 Feedback is applied in proposal order within each generation.
195 For manual evaluation, use ask_batch() and tell_batch().
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.
204 _requires_proposed_genome =
True
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)
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)
219 """Reset the proposal stream while retaining the archive."""
221 self.
_rng = np.random.default_rng(self.
seed)
226 base_ind[:] = self.
space.mutate(grid[self.
_rng.integers(len(grid))], self.
_rng)
228 base_ind[:] = self.
space.sample(self.
_rng)