"""Bit-exact (de)serialization of numpy arrays for deterministic persistence. A numpy array encodes to ``{"dtype", "shape", "b64"}`` where ``b64`` is base64 of the array's raw bytes. This is **bit-exact**: every float round-trips with zero precision loss, so a restored versor keeps ``versor_condition < 1e-6`` and a replayed turn keeps its ``trace_hash``. NEVER serialize field arrays as decimal/JSON floats. Decimal truncates the mantissa and silently breaks both closure and deterministic replay — the Cl(4,1) float-truncation pitfall. ``dtype`` carries byte order (``' dict[str, Any]: """Encode a numpy array to a bit-exact, JSON-safe dict.""" contiguous = np.ascontiguousarray(arr) return { "dtype": contiguous.dtype.str, # byte-order-aware, e.g. ' np.ndarray: """Decode a payload produced by ``encode_array`` back to an exact array. Returns a writable copy (``np.frombuffer`` is read-only) so the restored array can be composed and mutated like a freshly-built one. """ dtype = np.dtype(payload["dtype"]) raw = base64.b64decode(payload["b64"]) flat = np.frombuffer(raw, dtype=dtype) return flat.reshape(payload["shape"]).copy() def encode_optional_array(arr: np.ndarray | None) -> dict[str, Any] | None: """Encode an array, or return ``None`` for ``None`` (e.g. optional holonomy).""" return None if arr is None else encode_array(arr) def decode_optional_array(payload: dict[str, Any] | None) -> np.ndarray | None: """Decode an optional-array payload, or return ``None`` for ``None``.""" return None if payload is None else decode_array(payload)