"""Digital optical equivalent for a MHRN neuron state. The on-disk optical record is exactly 128 bytes. Five-dimensional coordinates are not duplicated because MHRN already packs five 8-bit coordinates into the neuron ID. """ from __future__ import annotations import struct from collections.abc import Iterable from dataclasses import dataclass, field from typing import Protocol RECORD_SIZE = 128 SPECTRAL_BINS = 32 class NeuronOpticalLike(Protocol): """Neuron attributes required to derive an optical sidecar state.""" v: float u: float energy: float threshold_adaptation: float def _u16_norm(value: float) -> int: return max(0, min(65_535, int(round(value * 65_535.0)))) def _i16_scaled(value: float, scale: float) -> int: return max(-32_768, min(32_767, int(round(value * scale)))) def _from_u16_norm(value: int) -> float: return value / 65_535.0 @dataclass(slots=True) class OpticalPointState: """Compact optical/electrical/chemical equivalent of one neuron.""" spectrum: tuple[int, ...] = field(default_factory=lambda: (0,) * SPECTRAL_BINS) brightness: float = 0.0 phase: float = 0.0 stokes: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0) coherence: float = 0.0 theta: float = 0.0 phi: float = 0.0 membrane_v: float = -65.0 recovery_u: float = -13.0 energy: float = 1.0 threshold_adaptation: float = 0.0 glutamate: float = 0.0 gaba: float = 0.0 dopamine: float = 0.0 serotonin: float = 0.0 acetylcholine: float = 0.0 norepinephrine: float = 0.0 calcium: float = 0.0 sodium: float = 0.0 potassium: float = 0.0 flags: int = 0 def validate(self) -> None: """Validate fixed-size optical record constraints.""" if len(self.spectrum) != SPECTRAL_BINS: raise ValueError(f"spectrum must contain {SPECTRAL_BINS} uint16 bins") if any(not 0 <= int(value) <= 65_535 for value in self.spectrum): raise ValueError("spectrum values must be 0..65535") def encode_optical_record( neuron_id: int, tick: int, state: OpticalPointState, ) -> bytes: """Encode one optical neuron snapshot into the fixed 128-byte record.""" state.validate() out = bytearray(RECORD_SIZE) struct.pack_into(" tuple[int, int, OpticalPointState]: """Decode a fixed 128-byte optical record.""" if len(data) != RECORD_SIZE: raise ValueError(f"record must be exactly {RECORD_SIZE} bytes") neuron_id, tick = struct.unpack_from(" OpticalPointState: """Create the optical equivalent from a typed neuron surface.""" spec = ( tuple(int(value) for value in spectrum) if spectrum is not None else (0,) * SPECTRAL_BINS ) return OpticalPointState( spectrum=spec, brightness=max(0.0, min(1.0, (float(neuron.v) + 90.0) / 120.0)), membrane_v=float(neuron.v), recovery_u=float(neuron.u), energy=float(neuron.energy), threshold_adaptation=float(neuron.threshold_adaptation), )