Something went wrong. Try again.
WIP generalized fluoddity web viewer and evolution app
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301"""CPPN genotype for Picbreeder x Fluoddity.
A Compositional Pattern Producing Network: a small graph of typed-activationnodes that maps a fixed-length input vector to a fixed-length output vector byfunction composition. Evolved with NEAT-lite operators (perturb weight, addconnection, add node, mutate activation, crossover).
In this project the CPPN encodes Fluoddity's *Rule* (locus A): it maps a 4Dsensor reading (L, R) -> 4D (force, strafe). See docs/cppn_picbreeder_design.md.
The CPPN is the genotype. fourier_rule.py compiles it to a Fluoddity Rule(translation option 2); minisim.py renders that Rule to a phenotype."""
from __future__ import annotations
import jsonimport mathfrom dataclasses import dataclass, field, asdict
import numpy as np
# ---------------------------------------------------------------------------# Activation functions. These are the "canonical functions" the CPPN paper# composes: identity, periodic (segmentation), symmetric (bilateral), bounded.# All operate elementwise on a numpy array.# ---------------------------------------------------------------------------ACTIVATIONS = { "identity": lambda x: x, "sin": lambda x: np.sin(x), "gauss": lambda x: np.exp(-(x ** 2)), # symmetric -> bilateral frames "abs": lambda x: np.abs(x), # symmetric, kinked "tanh": lambda x: np.tanh(x), # bounded}ACTIVATION_NAMES = list(ACTIVATIONS.keys())
@dataclassclass Node: id: int kind: str # "input" | "hidden" | "output" activation: str # key into ACTIVATIONS (ignored for inputs) bias: float = 0.0
@dataclassclass Connection: src: int dst: int weight: float enabled: bool = True
class CPPN: """A small feed-forward (DAG) compositional network.
Inputs and outputs have fixed counts. Hidden nodes and connections grow via structural mutation. Evaluation is a topological sweep; cycles are never introduced (add-connection checks reachability). """
def __init__(self, n_in: int, n_out: int, nodes: list[Node] | None = None, conns: list[Connection] | None = None, next_id: int | None = None, rng: np.random.Generator | None = None): self.n_in = n_in self.n_out = n_out self.rng = rng if rng is not None else np.random.default_rng()
if nodes is None: # Minimal genome: inputs + outputs, fully connected, no hidden. nodes = [Node(i, "input", "identity") for i in range(n_in)] nodes += [Node(n_in + j, "output", self.rng.choice(ACTIVATION_NAMES)) for j in range(n_out)] conns = [] for i in range(n_in): for j in range(n_out): conns.append(Connection(i, n_in + j, float(self.rng.normal(0, 1.0)))) next_id = n_in + n_out
self.nodes: dict[int, Node] = {n.id: n for n in nodes} self.conns: list[Connection] = conns self._next_id = next_id if next_id is not None else (max(self.nodes) + 1) self._order_cache: list[int] | None = None
# -- ids ----------------------------------------------------------------- @property def input_ids(self) -> list[int]: return [n.id for n in self.nodes.values() if n.kind == "input"]
@property def output_ids(self) -> list[int]: return sorted(n.id for n in self.nodes.values() if n.kind == "output")
# -- evaluation ---------------------------------------------------------- def _topo_order(self) -> list[int]: if self._order_cache is not None: return self._order_cache # Kahn's algorithm over enabled connections. incoming: dict[int, int] = {nid: 0 for nid in self.nodes} adj: dict[int, list[int]] = {nid: [] for nid in self.nodes} for c in self.conns: if c.enabled: adj[c.src].append(c.dst) incoming[c.dst] += 1 queue = [nid for nid, d in incoming.items() if d == 0] order = [] while queue: nid = queue.pop() order.append(nid) for dst in adj[nid]: incoming[dst] -= 1 if incoming[dst] == 0: queue.append(dst) self._order_cache = order return order
def eval(self, x: np.ndarray) -> np.ndarray: """Evaluate the network.
x: shape (..., n_in). Returns shape (..., n_out). """ x = np.asarray(x, dtype=np.float64) batch = x.shape[:-1] vals: dict[int, np.ndarray] = {} in_ids = self.input_ids for k, nid in enumerate(in_ids): vals[nid] = x[..., k]
# group enabled incoming connections by destination incoming: dict[int, list[Connection]] = {nid: [] for nid in self.nodes} for c in self.conns: if c.enabled: incoming[c.dst].append(c)
for nid in self._topo_order(): node = self.nodes[nid] if node.kind == "input": continue acc = np.full(batch, node.bias, dtype=np.float64) for c in incoming[nid]: if c.src in vals: acc = acc + c.weight * vals[c.src] vals[nid] = ACTIVATIONS[node.activation](acc)
out = np.stack([vals.get(oid, np.zeros(batch)) for oid in self.output_ids], axis=-1) return out
# -- mutation (NEAT-lite) ----------------------------------------------- def _invalidate(self): self._order_cache = None
def _creates_cycle(self, src: int, dst: int) -> bool: # Would adding src->dst create a cycle? True if dst can already reach src. adj: dict[int, list[int]] = {nid: [] for nid in self.nodes} for c in self.conns: if c.enabled: adj[c.src].append(c.dst) stack, seen = [dst], set() while stack: n = stack.pop() if n == src: return True for m in adj[n]: if m not in seen: seen.add(m) stack.append(m) return False
def mutate(self, p_weight=0.8, weight_sigma=0.5, p_add_conn=0.15, p_add_node=0.08, p_activation=0.1, p_bias=0.2) -> "CPPN": """Return a mutated copy.""" clone = self.copy() r = clone.rng
# perturb weights for c in clone.conns: if c.enabled and r.random() < p_weight: c.weight += float(r.normal(0, weight_sigma))
# perturb biases / activations on non-input nodes for n in clone.nodes.values(): if n.kind == "input": continue if r.random() < p_bias: n.bias += float(r.normal(0, 0.3)) if r.random() < p_activation: n.activation = str(r.choice(ACTIVATION_NAMES))
# add connection if r.random() < p_add_conn: clone._try_add_connection()
# add node (split an existing connection) if r.random() < p_add_node: clone._try_add_node()
clone._invalidate() return clone
def _try_add_connection(self): r = self.rng candidates = list(self.nodes.values()) for _ in range(20): src = r.choice(candidates) dst = r.choice(candidates) if dst.kind == "input" or src.id == dst.id: continue if any(c.src == src.id and c.dst == dst.id for c in self.conns): continue if self._creates_cycle(src.id, dst.id): continue self.conns.append(Connection(src.id, dst.id, float(r.normal(0, 1.0)))) return
def _try_add_node(self): r = self.rng enabled = [c for c in self.conns if c.enabled] if not enabled: return c = enabled[r.integers(len(enabled))] c.enabled = False new_id = self._next_id self._next_id += 1 self.nodes[new_id] = Node(new_id, "hidden", str(r.choice(ACTIVATION_NAMES))) # src -> new (weight 1) -> dst (original weight): preserves function self.conns.append(Connection(c.src, new_id, 1.0)) self.conns.append(Connection(new_id, c.dst, c.weight))
# -- crossover ----------------------------------------------------------- def crossover(self, other: "CPPN") -> "CPPN": """Simple crossover: take this genome's structure, average shared connection weights with the other parent where (src,dst) matches.""" child = self.copy() other_w = {(c.src, c.dst): c.weight for c in other.conns if c.enabled} for c in child.conns: key = (c.src, c.dst) if key in other_w and self.rng.random() < 0.5: c.weight = 0.5 * (c.weight + other_w[key]) child._invalidate() return child
# -- (de)serialization --------------------------------------------------- def copy(self) -> "CPPN": return CPPN( self.n_in, self.n_out, nodes=[Node(**asdict(n)) for n in self.nodes.values()], conns=[Connection(**asdict(c)) for c in self.conns], next_id=self._next_id, rng=self.rng, )
def to_dict(self) -> dict: return { "n_in": self.n_in, "n_out": self.n_out, "next_id": self._next_id, "nodes": [asdict(n) for n in self.nodes.values()], "conns": [asdict(c) for c in self.conns], }
@classmethod def from_dict(cls, d: dict, rng=None) -> "CPPN": return cls( d["n_in"], d["n_out"], nodes=[Node(**n) for n in d["nodes"]], conns=[Connection(**c) for c in d["conns"]], next_id=d["next_id"], rng=rng, )
def complexity(self) -> tuple[int, int]: hidden = sum(1 for n in self.nodes.values() if n.kind == "hidden") enabled = sum(1 for c in self.conns if c.enabled) return hidden, enabled
if __name__ == "__main__": # smoke test: build, eval, mutate, serialize round-trip rng = np.random.default_rng(0) net = CPPN(4, 4, rng=rng) x = rng.normal(size=(5, 4)) y = net.eval(x) print("eval shape:", y.shape) for _ in range(30): net = net.mutate() print("after 30 mutations, complexity (hidden, conns):", net.complexity()) d = net.to_dict() net2 = CPPN.from_dict(json.loads(json.dumps(d))) assert np.allclose(net.eval(x), net2.eval(x)), "round-trip mismatch" print("serialization round-trip OK")