Skip to content

Adapters

Domain-specific adapter layer. The base adapter defines the interface; holonomic adapters map between SCPN layers and external coordinate systems. All 16 L1-L16 adapters are registered in the global ComponentRegistry and accessible via the create_adapter(layer) factory.

Base Adapter

sc_neurocore.adapters.base

Base interface for sc-neurocore adapters.

Adapters map domain-specific dynamics (Biology, Physics, etc.) into stochastic bitstreams and JAX-accelerated kernels.

BaseStochasticAdapter

Bases: ABC

Abstract base class for all domain-specific adapters.

Source code in src/sc_neurocore/adapters/base.py
Python
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class BaseStochasticAdapter(ABC):
    """
    Abstract base class for all domain-specific adapters.
    """

    @abstractmethod
    def encode(self, state: Any) -> jnp.ndarray:
        """Map domain state to stochastic bitstreams."""
        ...

    @abstractmethod
    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """The JAX-accelerated mathematical kernel for the domain dynamics."""
        ...

    @abstractmethod
    def decode(self, bitstreams: jnp.ndarray) -> Any:
        """Map stochastic bitstreams back to domain-specific observables."""
        ...

    @abstractmethod
    def get_metrics(self) -> Dict[str, float]:
        """Return domain-specific metrics (e.g. Coherence, Concentration)."""
        ...

encode(state) abstractmethod

Map domain state to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/base.py
Python
29
30
31
32
@abstractmethod
def encode(self, state: Any) -> jnp.ndarray:
    """Map domain state to stochastic bitstreams."""
    ...

step_jax(dt, inputs=None) abstractmethod

The JAX-accelerated mathematical kernel for the domain dynamics.

Source code in src/sc_neurocore/adapters/base.py
Python
34
35
36
37
@abstractmethod
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """The JAX-accelerated mathematical kernel for the domain dynamics."""
    ...

decode(bitstreams) abstractmethod

Map stochastic bitstreams back to domain-specific observables.

Source code in src/sc_neurocore/adapters/base.py
Python
39
40
41
42
@abstractmethod
def decode(self, bitstreams: jnp.ndarray) -> Any:
    """Map stochastic bitstreams back to domain-specific observables."""
    ...

get_metrics() abstractmethod

Return domain-specific metrics (e.g. Coherence, Concentration).

Source code in src/sc_neurocore/adapters/base.py
Python
44
45
46
47
@abstractmethod
def get_metrics(self) -> Dict[str, float]:
    """Return domain-specific metrics (e.g. Coherence, Concentration)."""
    ...

Holonomic Atlas (L1-L16)

sc_neurocore.adapters.holonomic

Holonomic adapters for SCPN layers 1-16.

L1_QuantumAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN Quantum Biological layer.

Source code in src/sc_neurocore/adapters/holonomic/l1_quantum.py
Python
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
class L1_QuantumAdapter(BaseStochasticAdapter):
    """
    JAX-traceable adapter for the SCPN Quantum Biological layer.
    """

    def __init__(self, params: Optional[L1_HolonomicParameters] = None, seed: int = 41) -> None:
        self.params = params or L1_HolonomicParameters()
        self.rng_key = make_rng(seed)

        # State: Coherence Probabilities (0.0 to 1.0)
        self.coherence = jnp.full((self.params.n_qubits,), 0.95)
        # State: Metabolic Pumping Level
        self.s_pump = jnp.zeros((self.params.n_qubits,))

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """
        Maps coherence probabilities to stochastic bitstreams.
        """
        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_qubits, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < self.coherence[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _ignition_kernel(
        coherence: jnp.ndarray,
        s_pump: jnp.ndarray,
        s_crit: float,
        gamma: float,
        f_prot: float,
        dt: float,
    ) -> Tuple[jnp.ndarray, jnp.ndarray]:
        """
        Solves the Ignition / Metabolic Coherence dynamics:
        dC/dt = (S_pump - S_crit) * C - (gamma/log(F)) * C
        """
        # Effective decoherence reduced by protection factor
        effective_gamma = gamma / jnp.log10(f_prot)

        # Coherence growth depends on metabolic surplus
        growth = (s_pump - s_crit) * coherence
        dc = growth - effective_gamma * coherence

        coherence_next = jnp.clip(coherence + dc * dt, 0.0, 1.0)

        # Simplified S_pump recovery
        s_pump_next = jnp.clip(s_pump - 0.1 * dt, 0.0, 1.0)

        return coherence_next, s_pump_next

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L1 holonomic dynamics using JAX.

        inputs: (n_qubits, bitstream_length) representing metabolic/field drive (L4 or L13).
        Returns: (n_qubits, bitstream_length) output bitstreams.
        """
        # 1. Update Metabolic Pumping (S_pump) from inputs
        if inputs is not None:
            drive = jnp.mean(inputs.astype(jnp.float32), axis=1)
            self.s_pump = jnp.clip(self.s_pump + drive * dt, 0.0, 1.0)

        # 2. Execute Ignition Kernel
        self.coherence, self.s_pump = self._ignition_kernel(
            self.coherence,
            self.s_pump,
            self.params.s_critical,
            self.params.gamma_decoherence,
            self.params.f_non_markov,
            dt,
        )

        # 3. Phase-to-Angle Isomorphism (Optional: for use with true hardware)
        # theta = 2 * jnp.arcsin(jnp.sqrt(self.coherence))

        # 4. Return encoded bitstreams
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """
        Maps bitstreams back to global coherence metric.
        """
        return {"avg_coherence": float(jnp.mean(bitstreams.astype(jnp.float32)))}

    def get_metrics(self) -> Dict[str, float]:
        """
        Returns L1-specific metrics like Coherence and Pumping levels.
        """
        return {
            "r1_global_coherence": float(jnp.mean(self.coherence)),
            "avg_metabolic_pumping": float(jnp.mean(self.s_pump)),
        }

encode(domain_state)

Maps coherence probabilities to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l1_quantum.py
Python
66
67
68
69
70
71
72
73
def encode(self, domain_state: Any) -> jnp.ndarray:
    """
    Maps coherence probabilities to stochastic bitstreams.
    """
    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_qubits, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < self.coherence[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advances the L1 holonomic dynamics using JAX.

inputs: (n_qubits, bitstream_length) representing metabolic/field drive (L4 or L13). Returns: (n_qubits, bitstream_length) output bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l1_quantum.py
Python
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L1 holonomic dynamics using JAX.

    inputs: (n_qubits, bitstream_length) representing metabolic/field drive (L4 or L13).
    Returns: (n_qubits, bitstream_length) output bitstreams.
    """
    # 1. Update Metabolic Pumping (S_pump) from inputs
    if inputs is not None:
        drive = jnp.mean(inputs.astype(jnp.float32), axis=1)
        self.s_pump = jnp.clip(self.s_pump + drive * dt, 0.0, 1.0)

    # 2. Execute Ignition Kernel
    self.coherence, self.s_pump = self._ignition_kernel(
        self.coherence,
        self.s_pump,
        self.params.s_critical,
        self.params.gamma_decoherence,
        self.params.f_non_markov,
        dt,
    )

    # 3. Phase-to-Angle Isomorphism (Optional: for use with true hardware)
    # theta = 2 * jnp.arcsin(jnp.sqrt(self.coherence))

    # 4. Return encoded bitstreams
    return self.encode(None)

decode(bitstreams)

Maps bitstreams back to global coherence metric.

Source code in src/sc_neurocore/adapters/holonomic/l1_quantum.py
Python
131
132
133
134
135
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """
    Maps bitstreams back to global coherence metric.
    """
    return {"avg_coherence": float(jnp.mean(bitstreams.astype(jnp.float32)))}

get_metrics()

Returns L1-specific metrics like Coherence and Pumping levels.

Source code in src/sc_neurocore/adapters/holonomic/l1_quantum.py
Python
137
138
139
140
141
142
143
144
def get_metrics(self) -> Dict[str, float]:
    """
    Returns L1-specific metrics like Coherence and Pumping levels.
    """
    return {
        "r1_global_coherence": float(jnp.mean(self.coherence)),
        "avg_metabolic_pumping": float(jnp.mean(self.s_pump)),
    }

L2_NeurochemicalAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN Neurochemical layer.

Source code in src/sc_neurocore/adapters/holonomic/l2_chem.py
Python
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
class L2_NeurochemicalAdapter(BaseStochasticAdapter):
    """
    JAX-traceable adapter for the SCPN Neurochemical layer.
    """

    def __init__(self, params: Optional[L2_HolonomicParameters] = None, seed: int = 42) -> None:
        self.params = params or L2_HolonomicParameters()
        self._validate_params(self.params)
        self.rng_key = make_rng(seed)

        # State: Receptors (n_types, n_receptors)
        self.receptor_states = jnp.zeros((self.params.n_transmitters, self.params.n_receptors))
        # State: Information-Geometric Field potential
        self.phi_field = jnp.zeros((self.params.n_transmitters,))
        # State: Field velocity for the second-order IIIEF wave dynamics
        self.phi_velocity = jnp.zeros((self.params.n_transmitters,))
        # State: Concentrations
        self.concentrations = jnp.full((self.params.n_transmitters,), 0.5)

    @staticmethod
    def _validate_positive_int(name: str, value: int) -> None:
        if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
            raise ValueError(f"{name} must be a positive integer.")

    @classmethod
    def _validate_params(cls, params: L2_HolonomicParameters) -> None:
        cls._validate_positive_int("n_transmitters", params.n_transmitters)
        cls._validate_positive_int("n_receptors", params.n_receptors)
        cls._validate_positive_int("bitstream_length", params.bitstream_length)

        if not np.isfinite(params.alpha_iiief) or params.alpha_iiief < 0.0:
            raise ValueError("alpha_iiief must be finite and non-negative.")
        if not np.isfinite(params.c_info) or params.c_info <= 0.0:
            raise ValueError("c_info must be finite and positive.")
        if not np.isfinite(params.g_snare) or params.g_snare <= 0.0:
            raise ValueError("g_snare must be finite and positive.")
        if not np.isfinite(params.v_critical) or params.v_critical <= 0.0:
            raise ValueError("v_critical must be finite and positive.")
        if not np.isfinite(params.dopamine_gain) or params.dopamine_gain <= 0.0:
            raise ValueError("dopamine_gain must be finite and positive.")
        if not np.isfinite(params.serotonin_leak) or not 0.0 <= params.serotonin_leak <= 1.0:
            raise ValueError("serotonin_leak must be finite and in the interval [0, 1].")

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """
        Maps neurochemical concentrations to stochastic bitstreams.
        """
        # (n_transmitters, bitstream_length)
        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_transmitters, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < self.concentrations[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _iiief_kernel(
        phi: jnp.ndarray,
        velocity: jnp.ndarray,
        integrated_info: jnp.ndarray,
        alpha: float,
        c_info: float,
        dt: float,
    ) -> tuple[jnp.ndarray, jnp.ndarray]:
        """
        Advances the damped finite-difference IIIEF wave equation.
        """
        source = jnp.clip(integrated_info, 0.0, 1.0)
        laplacian = jnp.roll(phi, -1) - 2.0 * phi + jnp.roll(phi, 1)
        courant = c_info / (1.0 + c_info)
        acceleration = (
            4.0 * jnp.pi * alpha * source
            + courant * courant * laplacian
            - 0.15 * velocity
            - 0.05 * phi
        )
        velocity_next = velocity + acceleration * dt
        phi_next = phi + velocity_next * dt
        return phi_next, velocity_next

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L2 holonomic dynamics using JAX.

        inputs: (n_transmitters, bitstream_length) representing L1 or L5 feedback.
        Returns: (n_transmitters, bitstream_length) output bitstreams.
        """
        if not np.isfinite(dt) or dt <= 0.0:
            raise ValueError("dt must be finite and positive.")

        # 1. Calculate Integrated Information Proxy (Phi_integrated) from inputs
        if inputs is not None:
            raw_phi = jnp.mean(inputs.astype(jnp.float32), axis=1)
            # Map input dimensions to transmitter count if necessary
            if raw_phi.shape[0] != self.params.n_transmitters:
                # Simple average-pooling projection
                phi_int = jnp.full((self.params.n_transmitters,), jnp.mean(raw_phi))
            else:
                phi_int = raw_phi
        else:
            phi_int = jnp.zeros((self.params.n_transmitters,))

        # 2. Update IIIEF Field
        self.phi_field, self.phi_velocity = self._iiief_kernel(
            self.phi_field,
            self.phi_velocity,
            phi_int,
            self.params.alpha_iiief,
            self.params.c_info,
            dt,
        )

        # 3. H_QC Bridge: Field modulates concentrations (Vesicle release)
        # H_int = -lambda * Psi * sigma -> mapped to P_release modulation
        trigger = 1.0 / (
            1.0 + jnp.exp(-self.params.dopamine_gain * (self.phi_field - self.params.v_critical))
        )
        release_mod = (
            self.params.serotonin_leak
            + (1.0 - self.params.serotonin_leak) * self.params.g_snare * trigger
        )
        self.concentrations = jnp.clip(self.concentrations * release_mod, 0.0, 1.0)

        # 4. Return encoded bitstreams for hardware consumption
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """
        Maps bitstreams back to neurochemical concentrations.
        """
        means = jnp.mean(bitstreams.astype(jnp.float32), axis=1)
        return {
            "dopamine": float(means[0]),
            "serotonin": float(means[1]),
            "norepinephrine": float(means[2]),
            "acetylcholine": float(means[3]),
        }

    def get_metrics(self) -> Dict[str, float]:
        """
        Returns L2-specific metrics like Field Potential and Tonus.
        """
        return {
            "avg_field_potential": float(jnp.mean(self.phi_field)),
            "avg_field_velocity": float(jnp.mean(jnp.abs(self.phi_velocity))),
            "system_coherence_r2": float(jnp.mean(self.concentrations)),
        }

encode(domain_state)

Maps neurochemical concentrations to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l2_chem.py
Python
 98
 99
100
101
102
103
104
105
106
def encode(self, domain_state: Any) -> jnp.ndarray:
    """
    Maps neurochemical concentrations to stochastic bitstreams.
    """
    # (n_transmitters, bitstream_length)
    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_transmitters, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < self.concentrations[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advances the L2 holonomic dynamics using JAX.

inputs: (n_transmitters, bitstream_length) representing L1 or L5 feedback. Returns: (n_transmitters, bitstream_length) output bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l2_chem.py
Python
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L2 holonomic dynamics using JAX.

    inputs: (n_transmitters, bitstream_length) representing L1 or L5 feedback.
    Returns: (n_transmitters, bitstream_length) output bitstreams.
    """
    if not np.isfinite(dt) or dt <= 0.0:
        raise ValueError("dt must be finite and positive.")

    # 1. Calculate Integrated Information Proxy (Phi_integrated) from inputs
    if inputs is not None:
        raw_phi = jnp.mean(inputs.astype(jnp.float32), axis=1)
        # Map input dimensions to transmitter count if necessary
        if raw_phi.shape[0] != self.params.n_transmitters:
            # Simple average-pooling projection
            phi_int = jnp.full((self.params.n_transmitters,), jnp.mean(raw_phi))
        else:
            phi_int = raw_phi
    else:
        phi_int = jnp.zeros((self.params.n_transmitters,))

    # 2. Update IIIEF Field
    self.phi_field, self.phi_velocity = self._iiief_kernel(
        self.phi_field,
        self.phi_velocity,
        phi_int,
        self.params.alpha_iiief,
        self.params.c_info,
        dt,
    )

    # 3. H_QC Bridge: Field modulates concentrations (Vesicle release)
    # H_int = -lambda * Psi * sigma -> mapped to P_release modulation
    trigger = 1.0 / (
        1.0 + jnp.exp(-self.params.dopamine_gain * (self.phi_field - self.params.v_critical))
    )
    release_mod = (
        self.params.serotonin_leak
        + (1.0 - self.params.serotonin_leak) * self.params.g_snare * trigger
    )
    self.concentrations = jnp.clip(self.concentrations * release_mod, 0.0, 1.0)

    # 4. Return encoded bitstreams for hardware consumption
    return self.encode(None)

decode(bitstreams)

Maps bitstreams back to neurochemical concentrations.

Source code in src/sc_neurocore/adapters/holonomic/l2_chem.py
Python
180
181
182
183
184
185
186
187
188
189
190
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """
    Maps bitstreams back to neurochemical concentrations.
    """
    means = jnp.mean(bitstreams.astype(jnp.float32), axis=1)
    return {
        "dopamine": float(means[0]),
        "serotonin": float(means[1]),
        "norepinephrine": float(means[2]),
        "acetylcholine": float(means[3]),
    }

get_metrics()

Returns L2-specific metrics like Field Potential and Tonus.

Source code in src/sc_neurocore/adapters/holonomic/l2_chem.py
Python
192
193
194
195
196
197
198
199
200
def get_metrics(self) -> Dict[str, float]:
    """
    Returns L2-specific metrics like Field Potential and Tonus.
    """
    return {
        "avg_field_potential": float(jnp.mean(self.phi_field)),
        "avg_field_velocity": float(jnp.mean(jnp.abs(self.phi_velocity))),
        "system_coherence_r2": float(jnp.mean(self.concentrations)),
    }

L3_GenomicAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN Genomic/Epigenomic layer.

Source code in src/sc_neurocore/adapters/holonomic/l3_gen.py
Python
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
class L3_GenomicAdapter(BaseStochasticAdapter):
    """
    JAX-traceable adapter for the SCPN Genomic/Epigenomic layer.
    """

    def __init__(self, params: Optional[L3_HolonomicParameters] = None, seed: int = 43) -> None:
        self.params = params or L3_HolonomicParameters()
        self.rng_key = make_rng(seed)

        # State: Chromatin Accessibility (0.0 to 1.0)
        self.accessibility = jnp.full((self.params.n_genes,), 0.1)
        # State: Local Bioelectric Potential (mV normalized)
        self.v_bio = jnp.zeros((self.params.n_genes,))
        # State: Spin Polarization level
        self.p_spin = jnp.full((self.params.n_genes,), self.params.p_spin_baseline)

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """
        Maps accessibility states to stochastic bitstreams.
        """
        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_genes, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < self.accessibility[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _cbc_kernel(
        v_bio: jnp.ndarray, p_spin: jnp.ndarray, alpha_b: float, g_op: float, dt: float
    ) -> jnp.ndarray:
        """
        Solves the CBC Bridge transduction:
        Delta V = G * (alpha_B * P_spin)
        """
        dv = g_op * (alpha_b * p_spin) - 0.05 * v_bio
        return v_bio + dv * dt

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L3 CBC bridge dynamics using JAX.

        inputs: (n_genes, bitstream_length) representing L1/L2 feedback (e.g. Ca2+ levels).
        Returns: (n_genes, bitstream_length) output bitstreams.
        """
        # 1. Update Spin Polarization based on L1/L2 input (Stochastic Shielding)
        if inputs is not None:
            raw_drive = jnp.mean(inputs.astype(jnp.float32), axis=1)
            # Map input dimensions to gene count if necessary
            if raw_drive.shape[0] != self.params.n_genes:
                drive = jnp.full((self.params.n_genes,), jnp.mean(raw_drive))
            else:
                drive = raw_drive
            self.p_spin = jnp.clip(self.p_spin + 0.1 * drive * dt, 0.0, 1.0)

        # 2. Execute CBC Bridge Transduction (Field -> Bioelectric)
        self.v_bio = self._cbc_kernel(
            self.v_bio, self.p_spin, self.params.alpha_b, self.params.g_operator, dt
        )

        # 3. Update Chromatin Accessibility (Bioelectric -> Structural)
        # dA/dt = V_bio * Gain - k * A
        da = self.v_bio * 0.2 - 0.01 * self.accessibility
        self.accessibility = jnp.clip(self.accessibility + da * dt, 0.0, 1.0)

        # 4. Return encoded bitstreams
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """
        Maps bitstreams back to average genomic accessibility.
        """
        return {
            "avg_accessibility": float(jnp.mean(bitstreams.astype(jnp.float32))),
            "max_expression": float(jnp.max(jnp.mean(bitstreams.astype(jnp.float32), axis=1))),
        }

    def get_metrics(self) -> Dict[str, float]:
        """
        Returns L3-specific metrics like Spin Polarization and Bio-Potential.
        """
        return {
            "avg_p_spin": float(jnp.mean(self.p_spin)),
            "avg_v_bio": float(jnp.mean(self.v_bio)),
            "chromatin_coherence_r3": float(jnp.mean(self.accessibility)),
        }

encode(domain_state)

Maps accessibility states to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l3_gen.py
Python
66
67
68
69
70
71
72
73
def encode(self, domain_state: Any) -> jnp.ndarray:
    """
    Maps accessibility states to stochastic bitstreams.
    """
    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_genes, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < self.accessibility[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advances the L3 CBC bridge dynamics using JAX.

inputs: (n_genes, bitstream_length) representing L1/L2 feedback (e.g. Ca2+ levels). Returns: (n_genes, bitstream_length) output bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l3_gen.py
Python
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L3 CBC bridge dynamics using JAX.

    inputs: (n_genes, bitstream_length) representing L1/L2 feedback (e.g. Ca2+ levels).
    Returns: (n_genes, bitstream_length) output bitstreams.
    """
    # 1. Update Spin Polarization based on L1/L2 input (Stochastic Shielding)
    if inputs is not None:
        raw_drive = jnp.mean(inputs.astype(jnp.float32), axis=1)
        # Map input dimensions to gene count if necessary
        if raw_drive.shape[0] != self.params.n_genes:
            drive = jnp.full((self.params.n_genes,), jnp.mean(raw_drive))
        else:
            drive = raw_drive
        self.p_spin = jnp.clip(self.p_spin + 0.1 * drive * dt, 0.0, 1.0)

    # 2. Execute CBC Bridge Transduction (Field -> Bioelectric)
    self.v_bio = self._cbc_kernel(
        self.v_bio, self.p_spin, self.params.alpha_b, self.params.g_operator, dt
    )

    # 3. Update Chromatin Accessibility (Bioelectric -> Structural)
    # dA/dt = V_bio * Gain - k * A
    da = self.v_bio * 0.2 - 0.01 * self.accessibility
    self.accessibility = jnp.clip(self.accessibility + da * dt, 0.0, 1.0)

    # 4. Return encoded bitstreams
    return self.encode(None)

decode(bitstreams)

Maps bitstreams back to average genomic accessibility.

Source code in src/sc_neurocore/adapters/holonomic/l3_gen.py
Python
117
118
119
120
121
122
123
124
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """
    Maps bitstreams back to average genomic accessibility.
    """
    return {
        "avg_accessibility": float(jnp.mean(bitstreams.astype(jnp.float32))),
        "max_expression": float(jnp.max(jnp.mean(bitstreams.astype(jnp.float32), axis=1))),
    }

get_metrics()

Returns L3-specific metrics like Spin Polarization and Bio-Potential.

Source code in src/sc_neurocore/adapters/holonomic/l3_gen.py
Python
126
127
128
129
130
131
132
133
134
def get_metrics(self) -> Dict[str, float]:
    """
    Returns L3-specific metrics like Spin Polarization and Bio-Potential.
    """
    return {
        "avg_p_spin": float(jnp.mean(self.p_spin)),
        "avg_v_bio": float(jnp.mean(self.v_bio)),
        "chromatin_coherence_r3": float(jnp.mean(self.accessibility)),
    }

L4_CellularAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN Cellular-Tissue layer.

Source code in src/sc_neurocore/adapters/holonomic/l4_cell.py
Python
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
class L4_CellularAdapter(BaseStochasticAdapter):
    """
    JAX-traceable adapter for the SCPN Cellular-Tissue layer.
    """

    def __init__(self, params: Optional[L4_HolonomicParameters] = None, seed: int = 44) -> None:
        self.params = params or L4_HolonomicParameters()
        self.rng_key = make_rng(seed)

        # State: Oscillator Phases (0 to 2*pi)
        self.phases = uniform(self.rng_key, (self.params.n_cells,), minval=0.0, maxval=2 * jnp.pi)
        # State: Local Avalanche Magnitude
        self.avalanches = jnp.zeros((self.params.n_cells,))

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """
        Maps synchronization activity to stochastic bitstreams.
        """
        # Activity = (1 + cos(phase)) / 2
        activity = (1.0 + jnp.cos(self.phases)) / 2.0

        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_cells, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < activity[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _kuramoto_kernel(
        phases: jnp.ndarray, omega: float, k: float, dt: float, noise: jnp.ndarray
    ) -> jnp.ndarray:
        """
        Solves the Kuramoto-UPDE interaction:
        dTheta_i = [omega + K/N * sum(sin(Theta_j - Theta_i)) + noise] * dt
        """
        n = phases.shape[0]
        # Calculate all-to-all coupling (can be optimized with neighbor masks later)
        diffs = phases[None, :] - phases[:, None]
        coupling = (k / n) * jnp.sum(jnp.sin(diffs), axis=1)

        d_phase = (2 * jnp.pi * omega + coupling + noise) * dt
        return (phases + d_phase) % (2 * jnp.pi)

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L4 holonomic dynamics using JAX.

        inputs: (n_cells, bitstream_length) representing L3 Genomic drive.
        Returns: (n_cells, bitstream_length) output bitstreams.
        """
        # 1. Generate Noise
        self.rng_key, subkey = split_rng(self.rng_key)
        noise = normal(subkey, (self.params.n_cells,)) * self.params.sigma_noise

        # 2. Update Phases via Kuramoto Kernel
        self.phases = self._kuramoto_kernel(
            self.phases, self.params.omega_mean, self.params.k_coupling, dt, noise
        )

        # 3. Model Avalanche Dynamics (Criticality readout)
        # If mean activity crosses threshold, ignition occurs
        mean_activity = jnp.mean((1.0 + jnp.cos(self.phases)) / 2.0)
        ignition = (mean_activity > self.params.critical_threshold).astype(jnp.float32)
        self.avalanches = 0.9 * self.avalanches + 0.1 * ignition

        # 4. Return encoded bitstreams
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """
        Maps bitstreams back to Kuramoto order parameter.
        """
        # Complex order parameter R = |1/N * sum(exp(i*theta))|
        # Approximated from bitstream means
        return {"synchronization_r4": float(jnp.abs(jnp.mean(jnp.exp(1j * self.phases))))}

    def get_metrics(self) -> Dict[str, float]:
        """
        Returns L4-specific metrics.
        """
        return {
            "order_parameter": float(jnp.abs(jnp.mean(jnp.exp(1j * self.phases)))),
            "avalanche_density": float(jnp.mean(self.avalanches)),
        }

encode(domain_state)

Maps synchronization activity to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l4_cell.py
Python
62
63
64
65
66
67
68
69
70
71
72
def encode(self, domain_state: Any) -> jnp.ndarray:
    """
    Maps synchronization activity to stochastic bitstreams.
    """
    # Activity = (1 + cos(phase)) / 2
    activity = (1.0 + jnp.cos(self.phases)) / 2.0

    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_cells, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < activity[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advances the L4 holonomic dynamics using JAX.

inputs: (n_cells, bitstream_length) representing L3 Genomic drive. Returns: (n_cells, bitstream_length) output bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l4_cell.py
Python
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L4 holonomic dynamics using JAX.

    inputs: (n_cells, bitstream_length) representing L3 Genomic drive.
    Returns: (n_cells, bitstream_length) output bitstreams.
    """
    # 1. Generate Noise
    self.rng_key, subkey = split_rng(self.rng_key)
    noise = normal(subkey, (self.params.n_cells,)) * self.params.sigma_noise

    # 2. Update Phases via Kuramoto Kernel
    self.phases = self._kuramoto_kernel(
        self.phases, self.params.omega_mean, self.params.k_coupling, dt, noise
    )

    # 3. Model Avalanche Dynamics (Criticality readout)
    # If mean activity crosses threshold, ignition occurs
    mean_activity = jnp.mean((1.0 + jnp.cos(self.phases)) / 2.0)
    ignition = (mean_activity > self.params.critical_threshold).astype(jnp.float32)
    self.avalanches = 0.9 * self.avalanches + 0.1 * ignition

    # 4. Return encoded bitstreams
    return self.encode(None)

decode(bitstreams)

Maps bitstreams back to Kuramoto order parameter.

Source code in src/sc_neurocore/adapters/holonomic/l4_cell.py
Python
116
117
118
119
120
121
122
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """
    Maps bitstreams back to Kuramoto order parameter.
    """
    # Complex order parameter R = |1/N * sum(exp(i*theta))|
    # Approximated from bitstream means
    return {"synchronization_r4": float(jnp.abs(jnp.mean(jnp.exp(1j * self.phases))))}

get_metrics()

Returns L4-specific metrics.

Source code in src/sc_neurocore/adapters/holonomic/l4_cell.py
Python
124
125
126
127
128
129
130
131
def get_metrics(self) -> Dict[str, float]:
    """
    Returns L4-specific metrics.
    """
    return {
        "order_parameter": float(jnp.abs(jnp.mean(jnp.exp(1j * self.phases)))),
        "avalanche_density": float(jnp.mean(self.avalanches)),
    }

L5_OrganismalAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN Organismal-Psychoemotional layer.

Source code in src/sc_neurocore/adapters/holonomic/l5_org.py
Python
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
class L5_OrganismalAdapter(BaseStochasticAdapter):
    """
    JAX-traceable adapter for the SCPN Organismal-Psychoemotional layer.
    """

    def __init__(self, params: Optional[L5_HolonomicParameters] = None, seed: int = 45) -> None:
        self.params = params or L5_HolonomicParameters()
        self.rng_key = make_rng(seed)

        # State: Emotional Valence Vector (n_dims)
        self.emotions = jnp.full((self.params.n_emotional_dims,), 0.5)
        # State: Autonomic Tone (Sympathetic, Parasympathetic)
        self.autonomic = jnp.array([0.4, 0.6])  # [Symp, Para]
        # State: Strange Loop Recursive Model (Self-Soliton)
        self.self_soliton = jnp.zeros((self.params.n_nodes,))

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """
        Maps organismal state to stochastic bitstreams.
        """
        # Composite probability from emotions and autonomic tone
        avg_tone = jnp.mean(self.autonomic)
        probs = jnp.concatenate([self.emotions, self.autonomic])
        # Project to node count
        node_probs = jnp.tile(probs, (self.params.n_nodes // probs.shape[0]) + 1)[
            : self.params.n_nodes
        ]

        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_nodes, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < node_probs[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _autonomic_kernel(
        current: jnp.ndarray, target: jnp.ndarray, tau: float, dt: float
    ) -> jnp.ndarray:
        """
        Euler-integration of autonomic homeostasis.
        """
        return current + (target - current) * (dt / tau)

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L5 holonomic dynamics using JAX.

        inputs: (n_nodes, bitstream_length) representing L4 synchronization.
        Returns: (n_nodes, bitstream_length) output bitstreams.
        """
        # 1. Update Autonomic Tone based on L4 Synchronization
        if inputs is not None:
            sync = jnp.abs(jnp.mean(jnp.exp(1j * jnp.mean(inputs.astype(jnp.float32), axis=1))))
            # Higher sync drives Parasympathetic tone
            target_para = 0.5 + 0.4 * sync
            target_symp = 1.0 - target_para
            target = jnp.array([target_symp, target_para])
            self.autonomic = self._autonomic_kernel(
                self.autonomic, target, self.params.tau_autonomic, dt
            )

        # 2. Emotional Attractor Dynamics (Simplified)
        # Decay toward neutral [0.5]
        self.emotions = self.emotions + (0.5 - self.emotions) * self.params.emotional_decay * dt

        # 3. Recursive Strange Loop Update (The Self-Soliton)
        # self_soliton = f(self_soliton, emotions)
        self.self_soliton = 0.95 * self.self_soliton + 0.05 * jnp.mean(self.emotions)

        # 4. Return encoded bitstreams
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """
        Maps bitstreams back to average valence and HRV coherence.
        """
        return {
            "organismal_valence": float(jnp.mean(self.emotions)),
            "autonomic_balance": float(self.autonomic[1] / (self.autonomic[0] + 1e-6)),
        }

    def get_metrics(self) -> Dict[str, float]:
        """
        Returns L5-specific metrics.
        """
        return {
            "hrv_coherence_r5": float(self.autonomic[1]),
            "self_soliton_magnitude": float(jnp.mean(self.self_soliton)),
            "emotional_valence": float(self.emotions[0]),
        }

encode(domain_state)

Maps organismal state to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l5_org.py
Python
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def encode(self, domain_state: Any) -> jnp.ndarray:
    """
    Maps organismal state to stochastic bitstreams.
    """
    # Composite probability from emotions and autonomic tone
    avg_tone = jnp.mean(self.autonomic)
    probs = jnp.concatenate([self.emotions, self.autonomic])
    # Project to node count
    node_probs = jnp.tile(probs, (self.params.n_nodes // probs.shape[0]) + 1)[
        : self.params.n_nodes
    ]

    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_nodes, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < node_probs[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advances the L5 holonomic dynamics using JAX.

inputs: (n_nodes, bitstream_length) representing L4 synchronization. Returns: (n_nodes, bitstream_length) output bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l5_org.py
Python
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L5 holonomic dynamics using JAX.

    inputs: (n_nodes, bitstream_length) representing L4 synchronization.
    Returns: (n_nodes, bitstream_length) output bitstreams.
    """
    # 1. Update Autonomic Tone based on L4 Synchronization
    if inputs is not None:
        sync = jnp.abs(jnp.mean(jnp.exp(1j * jnp.mean(inputs.astype(jnp.float32), axis=1))))
        # Higher sync drives Parasympathetic tone
        target_para = 0.5 + 0.4 * sync
        target_symp = 1.0 - target_para
        target = jnp.array([target_symp, target_para])
        self.autonomic = self._autonomic_kernel(
            self.autonomic, target, self.params.tau_autonomic, dt
        )

    # 2. Emotional Attractor Dynamics (Simplified)
    # Decay toward neutral [0.5]
    self.emotions = self.emotions + (0.5 - self.emotions) * self.params.emotional_decay * dt

    # 3. Recursive Strange Loop Update (The Self-Soliton)
    # self_soliton = f(self_soliton, emotions)
    self.self_soliton = 0.95 * self.self_soliton + 0.05 * jnp.mean(self.emotions)

    # 4. Return encoded bitstreams
    return self.encode(None)

decode(bitstreams)

Maps bitstreams back to average valence and HRV coherence.

Source code in src/sc_neurocore/adapters/holonomic/l5_org.py
Python
121
122
123
124
125
126
127
128
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """
    Maps bitstreams back to average valence and HRV coherence.
    """
    return {
        "organismal_valence": float(jnp.mean(self.emotions)),
        "autonomic_balance": float(self.autonomic[1] / (self.autonomic[0] + 1e-6)),
    }

get_metrics()

Returns L5-specific metrics.

Source code in src/sc_neurocore/adapters/holonomic/l5_org.py
Python
130
131
132
133
134
135
136
137
138
def get_metrics(self) -> Dict[str, float]:
    """
    Returns L5-specific metrics.
    """
    return {
        "hrv_coherence_r5": float(self.autonomic[1]),
        "self_soliton_magnitude": float(jnp.mean(self.self_soliton)),
        "emotional_valence": float(self.emotions[0]),
    }

L6_PlanetaryAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN planetary-biospheric layer.

Source code in src/sc_neurocore/adapters/holonomic/l6_plan.py
Python
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
class L6_PlanetaryAdapter(BaseStochasticAdapter):
    """JAX-traceable adapter for the SCPN planetary-biospheric layer."""

    def __init__(self, params: Optional[L6_HolonomicParameters] = None, seed: int = 46) -> None:
        """Initialise the Layer 6 planetary adapter.

        Parameters
        ----------
        params:
            Optional Gaia-field configuration. Defaults keep the historical
            100-region, 1024-bitstream contract.
        seed:
            Random seed forwarded to the JAX or NumPy compatibility RNG.

        Raises
        ------
        ValueError
            If configuration values cannot produce bounded finite dynamics.
        """
        self.params = params or L6_HolonomicParameters()
        self._validate_params(self.params)
        self.rng_key = make_rng(seed)

        # State: Planetary Field Potential (Psi_P)
        self.phi_planetary = jnp.zeros((self.params.n_regions,))
        # State: Regional Coherence index
        self.regional_coherence = jnp.full((self.params.n_regions,), 0.1)
        # Time tracking for oscillatory resonance
        self.t = 0.0

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """Map planetary coherence to stochastic regional bitstreams.

        Parameters
        ----------
        domain_state:
            Reserved adapter payload for interface compatibility. Layer 6 uses
            its internal regional coherence state for encoding.

        Returns
        -------
        jnp.ndarray
            Rank-2 bitstream matrix with shape ``(n_regions, bitstream_length)``.
        """
        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_regions, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < self.regional_coherence[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _gaia_kernel(
        phi: jnp.ndarray,
        sync_inputs: jnp.ndarray,
        alpha: float,
        freq: float,
        q_factor: float,
        p_percolation: float,
        t: float,
        dt: float,
    ) -> Tuple[jnp.ndarray, jnp.ndarray]:
        """Solve the planetary Gaia-field dynamics.

        Parameters
        ----------
        phi:
            Current planetary field potential.
        sync_inputs:
            Bounded regional synchronisation drive.
        alpha:
            Gaia coupling strength.
        freq:
            Schumann resonance frequency.
        q_factor:
            Resonance quality factor controlling coherent gain.
        p_percolation:
            Critical percolation threshold.
        t:
            Simulation time after the current step increment.
        dt:
            Positive finite simulation timestep.

        Returns
        -------
        tuple[jnp.ndarray, jnp.ndarray]
            Updated field potential and regional coherence vectors.
        """
        bounded_sync = jnp.clip(sync_inputs, 0.0, 1.0)
        order_parameter = jnp.clip(jnp.mean(bounded_sync), 0.0, 1.0)

        # Schumann resonance driving term
        driver = jnp.cos(2.0 * jnp.pi * freq * t)
        superradiant_gain = 1.0 + q_factor * order_parameter**2
        d_phi = alpha * bounded_sync * superradiant_gain * driver - 0.05 * phi

        phi_next = phi + d_phi * dt

        percolation_gate = 1.0 / (1.0 + jnp.exp(-q_factor * (order_parameter - p_percolation)))
        local_field_activation = 1.0 - jnp.exp(-q_factor * jnp.abs(phi_next))
        coherence_next = jnp.clip(percolation_gate * local_field_activation, 0.0, 1.0)

        return phi_next, coherence_next

    @staticmethod
    def _validate_positive_int(name: str, value: int) -> None:
        """Validate a strict positive integer configuration field."""
        if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
            raise ValueError(f"{name} must be a positive integer.")

    @classmethod
    def _validate_params(cls, params: L6_HolonomicParameters) -> None:
        """Validate Layer 6 parameters before allocating backend arrays."""
        cls._validate_positive_int("n_regions", params.n_regions)
        cls._validate_positive_int("bitstream_length", params.bitstream_length)
        for field_name in ("f_schumann", "q_factor", "alpha_gaia"):
            value = float(getattr(params, field_name))
            if not np.isfinite(value) or value <= 0.0:
                raise ValueError(f"{field_name} must be finite and positive.")
        if not np.isfinite(params.p_percolation) or not 0.0 < params.p_percolation < 1.0:
            raise ValueError("p_percolation must be finite and in (0, 1).")

    @staticmethod
    def _validate_dt(dt: float) -> None:
        """Validate a positive finite simulation timestep."""
        if not np.isfinite(dt) or dt <= 0.0:
            raise ValueError("dt must be finite and positive.")

    def _validate_input_batch(self, inputs: jnp.ndarray) -> jnp.ndarray:
        """Validate and normalise an upstream L6 bitstream batch."""
        input_batch: jnp.ndarray = jnp.asarray(inputs)
        if input_batch.ndim != 2:
            raise ValueError("inputs must be a rank-2 bitstream batch.")
        if input_batch.shape[0] <= 0:
            raise ValueError("inputs must contain at least one row.")
        if input_batch.shape[1] != self.params.bitstream_length:
            raise ValueError("inputs bitstream_length must match adapter parameters.")
        if not bool(np.all(np.isfinite(np.asarray(input_batch)))):
            raise ValueError("inputs must contain only finite values.")
        return input_batch

    def _project_sync_drive(self, inputs: Optional[jnp.ndarray]) -> jnp.ndarray:
        """Project optional upstream bitstreams onto the configured L6 regions."""
        if inputs is None:
            return jnp.zeros((self.params.n_regions,))

        input_batch = self._validate_input_batch(inputs)
        sync_drive = jnp.mean(input_batch.astype(jnp.float32), axis=1)
        if sync_drive.shape[0] != self.params.n_regions:
            sync_drive = jnp.full((self.params.n_regions,), jnp.mean(sync_drive))
        return sync_drive

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """Advance the L6 holonomic dynamics using JAX-compatible arrays.

        Parameters
        ----------
        dt:
            Positive finite simulation timestep.
        inputs:
            Optional ``(N, bitstream_length)`` upstream organismal output. If
            ``N`` differs from ``n_regions``, the mean regional drive is
            broadcast across all configured regions.

        Returns
        -------
        jnp.ndarray
            Output bitstreams with shape ``(n_regions, bitstream_length)``.

        Raises
        ------
        ValueError
            If ``dt`` or ``inputs`` violates the bounded adapter contract.
        """
        self._validate_dt(dt)
        sync_drive = self._project_sync_drive(inputs)
        self.t += dt

        # 2. Execute Gaia Kernel
        self.phi_planetary, self.regional_coherence = self._gaia_kernel(
            self.phi_planetary,
            sync_drive,
            self.params.alpha_gaia,
            self.params.f_schumann,
            self.params.q_factor,
            self.params.p_percolation,
            self.t,
            dt,
        )

        # 3. Return encoded bitstreams
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """Map bitstreams back to the global coherence index.

        Parameters
        ----------
        bitstreams:
            Regional stochastic bitstream matrix.

        Returns
        -------
        dict[str, float]
            Telemetry dictionary containing ``global_coherence_index``.
        """
        return {"global_coherence_index": float(jnp.mean(bitstreams.astype(jnp.float32)))}

    def get_metrics(self) -> Dict[str, float]:
        """Return L6-specific Gaia and Schumann telemetry.

        Returns
        -------
        dict[str, float]
            Current Gaia potential, percolation index, and Schumann phase.
        """
        return {
            "gaia_potential": float(jnp.mean(self.phi_planetary)),
            "percolation_index": float(jnp.mean(self.regional_coherence)),
            "schumann_phase": float(self.t * self.params.f_schumann % 1.0),
        }

__init__(params=None, seed=46)

Initialise the Layer 6 planetary adapter.

Parameters

params: Optional Gaia-field configuration. Defaults keep the historical 100-region, 1024-bitstream contract. seed: Random seed forwarded to the JAX or NumPy compatibility RNG.

Raises

ValueError If configuration values cannot produce bounded finite dynamics.

Source code in src/sc_neurocore/adapters/holonomic/l6_plan.py
Python
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def __init__(self, params: Optional[L6_HolonomicParameters] = None, seed: int = 46) -> None:
    """Initialise the Layer 6 planetary adapter.

    Parameters
    ----------
    params:
        Optional Gaia-field configuration. Defaults keep the historical
        100-region, 1024-bitstream contract.
    seed:
        Random seed forwarded to the JAX or NumPy compatibility RNG.

    Raises
    ------
    ValueError
        If configuration values cannot produce bounded finite dynamics.
    """
    self.params = params or L6_HolonomicParameters()
    self._validate_params(self.params)
    self.rng_key = make_rng(seed)

    # State: Planetary Field Potential (Psi_P)
    self.phi_planetary = jnp.zeros((self.params.n_regions,))
    # State: Regional Coherence index
    self.regional_coherence = jnp.full((self.params.n_regions,), 0.1)
    # Time tracking for oscillatory resonance
    self.t = 0.0

encode(domain_state)

Map planetary coherence to stochastic regional bitstreams.

Parameters

domain_state: Reserved adapter payload for interface compatibility. Layer 6 uses its internal regional coherence state for encoding.

Returns

jnp.ndarray Rank-2 bitstream matrix with shape (n_regions, bitstream_length).

Source code in src/sc_neurocore/adapters/holonomic/l6_plan.py
Python
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def encode(self, domain_state: Any) -> jnp.ndarray:
    """Map planetary coherence to stochastic regional bitstreams.

    Parameters
    ----------
    domain_state:
        Reserved adapter payload for interface compatibility. Layer 6 uses
        its internal regional coherence state for encoding.

    Returns
    -------
    jnp.ndarray
        Rank-2 bitstream matrix with shape ``(n_regions, bitstream_length)``.
    """
    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_regions, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < self.regional_coherence[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advance the L6 holonomic dynamics using JAX-compatible arrays.

Parameters

dt: Positive finite simulation timestep. inputs: Optional (N, bitstream_length) upstream organismal output. If N differs from n_regions, the mean regional drive is broadcast across all configured regions.

Returns

jnp.ndarray Output bitstreams with shape (n_regions, bitstream_length).

Raises

ValueError If dt or inputs violates the bounded adapter contract.

Source code in src/sc_neurocore/adapters/holonomic/l6_plan.py
Python
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """Advance the L6 holonomic dynamics using JAX-compatible arrays.

    Parameters
    ----------
    dt:
        Positive finite simulation timestep.
    inputs:
        Optional ``(N, bitstream_length)`` upstream organismal output. If
        ``N`` differs from ``n_regions``, the mean regional drive is
        broadcast across all configured regions.

    Returns
    -------
    jnp.ndarray
        Output bitstreams with shape ``(n_regions, bitstream_length)``.

    Raises
    ------
    ValueError
        If ``dt`` or ``inputs`` violates the bounded adapter contract.
    """
    self._validate_dt(dt)
    sync_drive = self._project_sync_drive(inputs)
    self.t += dt

    # 2. Execute Gaia Kernel
    self.phi_planetary, self.regional_coherence = self._gaia_kernel(
        self.phi_planetary,
        sync_drive,
        self.params.alpha_gaia,
        self.params.f_schumann,
        self.params.q_factor,
        self.params.p_percolation,
        self.t,
        dt,
    )

    # 3. Return encoded bitstreams
    return self.encode(None)

decode(bitstreams)

Map bitstreams back to the global coherence index.

Parameters

bitstreams: Regional stochastic bitstream matrix.

Returns

dict[str, float] Telemetry dictionary containing global_coherence_index.

Source code in src/sc_neurocore/adapters/holonomic/l6_plan.py
Python
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """Map bitstreams back to the global coherence index.

    Parameters
    ----------
    bitstreams:
        Regional stochastic bitstream matrix.

    Returns
    -------
    dict[str, float]
        Telemetry dictionary containing ``global_coherence_index``.
    """
    return {"global_coherence_index": float(jnp.mean(bitstreams.astype(jnp.float32)))}

get_metrics()

Return L6-specific Gaia and Schumann telemetry.

Returns

dict[str, float] Current Gaia potential, percolation index, and Schumann phase.

Source code in src/sc_neurocore/adapters/holonomic/l6_plan.py
Python
271
272
273
274
275
276
277
278
279
280
281
282
283
def get_metrics(self) -> Dict[str, float]:
    """Return L6-specific Gaia and Schumann telemetry.

    Returns
    -------
    dict[str, float]
        Current Gaia potential, percolation index, and Schumann phase.
    """
    return {
        "gaia_potential": float(jnp.mean(self.phi_planetary)),
        "percolation_index": float(jnp.mean(self.regional_coherence)),
        "schumann_phase": float(self.t * self.params.f_schumann % 1.0),
    }

L7_SymbolicAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN geometrical-symbolic layer.

Source code in src/sc_neurocore/adapters/holonomic/l7_sym.py
Python
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
class L7_SymbolicAdapter(BaseStochasticAdapter):
    """JAX-traceable adapter for the SCPN geometrical-symbolic layer."""

    def __init__(self, params: Optional[L7_HolonomicParameters] = None, seed: int = 47) -> None:
        self.params = params or L7_HolonomicParameters()
        self._validate_params(self.params)
        self.rng_key = make_rng(seed)

        # State: Node Phases (representing symbolic glyphs)
        self.node_phases = jnp.zeros((self.params.n_nodes,))
        # State: Metatron's Cube Adjacency Matrix (13x13)
        self.metatron_matrix = self._init_metatron_matrix()

    def _init_metatron_matrix(self) -> jnp.ndarray:
        """Initialise a symmetric bounded Metatron routing topology."""
        n = self.params.n_nodes
        if n == 1:
            return jnp.array([[1.0]], dtype=jnp.float32)

        coords = self._metatron_coordinates(n)
        deltas = coords[:, None, :] - coords[None, :, :]
        distances = np.linalg.norm(deltas, axis=2)

        with np.errstate(over="ignore", under="ignore"):
            off_diag = np.exp(-distances / self.params.phi_golden_ratio)
        off_diag *= self.params.g_geometric_gain
        np.fill_diagonal(off_diag, 0.0)

        row_sums = off_diag.sum(axis=1)
        max_row_sum = float(np.max(row_sums))
        if max_row_sum <= 0.0:
            raise ValueError("Metatron topology requires at least one off-diagonal edge.")

        off_diag *= (1.0 - self.params.coupling_leak) / max_row_sum
        matrix = off_diag
        np.fill_diagonal(matrix, 1.0 - matrix.sum(axis=1))
        return jnp.array(matrix, dtype=jnp.float32)

    @staticmethod
    def _metatron_coordinates(n_nodes: int) -> np.ndarray[Any, Any]:
        if n_nodes == 13:
            angles = np.linspace(0.0, 2.0 * np.pi, 6, endpoint=False)
            inner = np.stack([np.cos(angles), np.sin(angles)], axis=1)
            outer = 2.0 * inner
            return np.vstack([np.zeros((1, 2)), inner, outer]).astype(np.float64)

        angles = np.linspace(0.0, 2.0 * np.pi, n_nodes - 1, endpoint=False)
        ring = np.stack([np.cos(angles), np.sin(angles)], axis=1)
        return np.vstack([np.zeros((1, 2)), ring]).astype(np.float64)

    @staticmethod
    def _validate_params(params: L7_HolonomicParameters) -> None:
        if not isinstance(params.n_nodes, int) or isinstance(params.n_nodes, bool):
            raise ValueError("n_nodes must be a positive integer.")
        if params.n_nodes <= 0:
            raise ValueError("n_nodes must be positive.")
        if not isinstance(params.bitstream_length, int) or isinstance(
            params.bitstream_length, bool
        ):
            raise ValueError("bitstream_length must be a positive integer.")
        if params.bitstream_length <= 0:
            raise ValueError("bitstream_length must be positive.")
        if not np.isfinite(params.g_geometric_gain) or params.g_geometric_gain <= 0.0:
            raise ValueError("g_geometric_gain must be finite and positive.")
        if not np.isfinite(params.phi_golden_ratio) or params.phi_golden_ratio <= 0.0:
            raise ValueError("phi_golden_ratio must be finite and positive.")
        if not np.isfinite(params.coupling_leak) or not 0.0 <= params.coupling_leak < 1.0:
            raise ValueError("coupling_leak must be finite and in [0, 1).")

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """Map symbolic phases to stochastic bitstreams."""
        # Activation = (1 + cos(phase)) / 2
        activation = (1.0 + jnp.cos(self.node_phases)) / 2.0

        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_nodes, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < activation[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _symbolic_kernel(
        phases: jnp.ndarray, metatron: jnp.ndarray, inputs: jnp.ndarray, dt: float
    ) -> jnp.ndarray:
        """Solve the symbolic routing dynamics.

        The update follows ``dTheta/dt = Metatron * inputs - decay``.
        """
        # Phases rotate based on weighted inputs from the Metatron routing
        drive = jnp.dot(metatron, inputs)
        d_phase = drive - 0.1 * phases
        return phases + d_phase * dt

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L7 holonomic dynamics using JAX.

        inputs: (n_nodes, bitstream_length) representing L6 or L8 signals.
        Returns: (n_nodes, bitstream_length) output bitstreams.
        """
        # 1. Extract Input Influence
        if inputs is not None:
            input_drive = jnp.mean(inputs.astype(jnp.float32), axis=1)
            if input_drive.shape[0] != self.params.n_nodes:
                input_drive = jnp.full((self.params.n_nodes,), jnp.mean(input_drive))
        else:
            input_drive = jnp.zeros((self.params.n_nodes,))

        # 2. Execute Symbolic Kernel
        self.node_phases = self._symbolic_kernel(
            self.node_phases, self.metatron_matrix, input_drive, dt
        )

        # 3. Return encoded bitstreams
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """Map bitstreams back to symbolic coherence telemetry."""
        return {"symbolic_unity_r7": float(jnp.abs(jnp.mean(jnp.exp(1j * self.node_phases))))}

    def get_metrics(self) -> Dict[str, float]:
        """Return L7-specific routing and phase-stability metrics."""
        return {
            "routing_coherence": float(jnp.abs(jnp.mean(jnp.exp(1j * self.node_phases)))),
            "metatron_stability": float(jnp.mean(jnp.cos(self.node_phases))),
        }

encode(domain_state)

Map symbolic phases to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l7_sym.py
Python
116
117
118
119
120
121
122
123
124
def encode(self, domain_state: Any) -> jnp.ndarray:
    """Map symbolic phases to stochastic bitstreams."""
    # Activation = (1 + cos(phase)) / 2
    activation = (1.0 + jnp.cos(self.node_phases)) / 2.0

    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_nodes, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < activation[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advances the L7 holonomic dynamics using JAX.

inputs: (n_nodes, bitstream_length) representing L6 or L8 signals. Returns: (n_nodes, bitstream_length) output bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l7_sym.py
Python
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L7 holonomic dynamics using JAX.

    inputs: (n_nodes, bitstream_length) representing L6 or L8 signals.
    Returns: (n_nodes, bitstream_length) output bitstreams.
    """
    # 1. Extract Input Influence
    if inputs is not None:
        input_drive = jnp.mean(inputs.astype(jnp.float32), axis=1)
        if input_drive.shape[0] != self.params.n_nodes:
            input_drive = jnp.full((self.params.n_nodes,), jnp.mean(input_drive))
    else:
        input_drive = jnp.zeros((self.params.n_nodes,))

    # 2. Execute Symbolic Kernel
    self.node_phases = self._symbolic_kernel(
        self.node_phases, self.metatron_matrix, input_drive, dt
    )

    # 3. Return encoded bitstreams
    return self.encode(None)

decode(bitstreams)

Map bitstreams back to symbolic coherence telemetry.

Source code in src/sc_neurocore/adapters/holonomic/l7_sym.py
Python
163
164
165
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """Map bitstreams back to symbolic coherence telemetry."""
    return {"symbolic_unity_r7": float(jnp.abs(jnp.mean(jnp.exp(1j * self.node_phases))))}

get_metrics()

Return L7-specific routing and phase-stability metrics.

Source code in src/sc_neurocore/adapters/holonomic/l7_sym.py
Python
167
168
169
170
171
172
def get_metrics(self) -> Dict[str, float]:
    """Return L7-specific routing and phase-stability metrics."""
    return {
        "routing_coherence": float(jnp.abs(jnp.mean(jnp.exp(1j * self.node_phases)))),
        "metatron_stability": float(jnp.mean(jnp.cos(self.node_phases))),
    }

L8_CosmicAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN Cosmic Phase-Locking layer.

Source code in src/sc_neurocore/adapters/holonomic/l8_cosm.py
Python
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
class L8_CosmicAdapter(BaseStochasticAdapter):
    """
    JAX-traceable adapter for the SCPN Cosmic Phase-Locking layer.
    """

    def __init__(self, params: Optional[L8_HolonomicParameters] = None, seed: int = 48) -> None:
        self.params = params or L8_HolonomicParameters()
        self.rng_key = make_rng(seed)

        # State: Local System Phases (locked to pulsars)
        self.system_phases = jnp.zeros((self.params.n_pulsars,))
        # State: Cosmic Clock time
        self.t_cosmic = 0.0

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """
        Maps cosmic phases to stochastic bitstreams.
        """
        activation = (1.0 + jnp.cos(self.system_phases)) / 2.0

        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_pulsars, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < activation[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _cosmic_kernel(
        phases: jnp.ndarray, pulsar_omegas: jnp.ndarray, k_cosmic: float, dt: float
    ) -> jnp.ndarray:
        """
        Solves the Cosmic Phase-Locking dynamics:
        dTheta = [Omega_p + K * sin(Theta_p - Theta)] * dt
        """
        # Theta_pulsar is simulated as Omega_p * t
        # For simplicity in the JIT kernel, we assume pulsar phases are pre-calculated
        # or we just drive the local oscillators by their omegas with a coupling term.
        d_phase = pulsar_omegas + k_cosmic * jnp.sin(-phases)
        return (phases + d_phase * dt) % (2 * jnp.pi)

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L8 holonomic dynamics using JAX.

        inputs: (n_pulsars, bitstream_length) representing L7 Symbolic feedback.
        Returns: (n_pulsars, bitstream_length) output bitstreams.
        """
        self.t_cosmic += dt

        # 1. Update system phases via Cosmic Kernel
        self.system_phases = self._cosmic_kernel(
            self.system_phases, self.params.pulsar_omegas, self.params.k_cosmic, dt
        )

        # 2. Apply feedback from L7 (Symbolic) if present
        if inputs is not None:
            symbolic_drive = jnp.mean(inputs.astype(jnp.float32), axis=1)
            # Map input dimensions
            if symbolic_drive.shape[0] != self.params.n_pulsars:
                symbolic_drive = jnp.full((self.params.n_pulsars,), jnp.mean(symbolic_drive))
            self.system_phases = (self.system_phases + 0.1 * symbolic_drive * dt) % (2 * jnp.pi)

        # 3. Return encoded bitstreams
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """
        Maps bitstreams back to Cosmic Alignment.
        """
        return {"cosmic_alignment_r8": float(jnp.abs(jnp.mean(jnp.exp(1j * self.system_phases))))}

    def get_metrics(self) -> Dict[str, float]:
        """
        Returns L8-specific metrics.
        """
        return {
            "clock_stability": float(jnp.std(self.system_phases)),
            "pta_locking_index": float(jnp.abs(jnp.mean(jnp.exp(1j * self.system_phases)))),
        }

encode(domain_state)

Maps cosmic phases to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l8_cosm.py
Python
65
66
67
68
69
70
71
72
73
74
def encode(self, domain_state: Any) -> jnp.ndarray:
    """
    Maps cosmic phases to stochastic bitstreams.
    """
    activation = (1.0 + jnp.cos(self.system_phases)) / 2.0

    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_pulsars, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < activation[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advances the L8 holonomic dynamics using JAX.

inputs: (n_pulsars, bitstream_length) representing L7 Symbolic feedback. Returns: (n_pulsars, bitstream_length) output bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l8_cosm.py
Python
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L8 holonomic dynamics using JAX.

    inputs: (n_pulsars, bitstream_length) representing L7 Symbolic feedback.
    Returns: (n_pulsars, bitstream_length) output bitstreams.
    """
    self.t_cosmic += dt

    # 1. Update system phases via Cosmic Kernel
    self.system_phases = self._cosmic_kernel(
        self.system_phases, self.params.pulsar_omegas, self.params.k_cosmic, dt
    )

    # 2. Apply feedback from L7 (Symbolic) if present
    if inputs is not None:
        symbolic_drive = jnp.mean(inputs.astype(jnp.float32), axis=1)
        # Map input dimensions
        if symbolic_drive.shape[0] != self.params.n_pulsars:
            symbolic_drive = jnp.full((self.params.n_pulsars,), jnp.mean(symbolic_drive))
        self.system_phases = (self.system_phases + 0.1 * symbolic_drive * dt) % (2 * jnp.pi)

    # 3. Return encoded bitstreams
    return self.encode(None)

decode(bitstreams)

Maps bitstreams back to Cosmic Alignment.

Source code in src/sc_neurocore/adapters/holonomic/l8_cosm.py
Python
116
117
118
119
120
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """
    Maps bitstreams back to Cosmic Alignment.
    """
    return {"cosmic_alignment_r8": float(jnp.abs(jnp.mean(jnp.exp(1j * self.system_phases))))}

get_metrics()

Returns L8-specific metrics.

Source code in src/sc_neurocore/adapters/holonomic/l8_cosm.py
Python
122
123
124
125
126
127
128
129
def get_metrics(self) -> Dict[str, float]:
    """
    Returns L8-specific metrics.
    """
    return {
        "clock_stability": float(jnp.std(self.system_phases)),
        "pta_locking_index": float(jnp.abs(jnp.mean(jnp.exp(1j * self.system_phases)))),
    }

L9_MemoryAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN existential-memory layer.

Source code in src/sc_neurocore/adapters/holonomic/l9_mem.py
Python
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
class L9_MemoryAdapter(BaseStochasticAdapter):
    """JAX-traceable adapter for the SCPN existential-memory layer."""

    def __init__(self, params: Optional[L9_HolonomicParameters] = None, seed: int = 49) -> None:
        """Initialise the Layer 9 memory adapter.

        Parameters
        ----------
        params:
            Optional Layer 9 configuration. Defaults preserve the historical
            64-slot, 1024-bitstream contract.
        seed:
            Random seed forwarded to the JAX or NumPy compatibility RNG.

        Raises
        ------
        ValueError
            If any parameter would create an invalid memory tensor or unsafe
            retrieval contract.
        """
        self.params = params or L9_HolonomicParameters()
        self._validate_params(self.params)
        self.rng_key = make_rng(seed)

        # State: Forward Bitstream Imprints (Psi)
        self.imprints_psi = jnp.zeros(
            (self.params.n_memory_slots, self.params.bitstream_length), dtype=jnp.uint8
        )
        # State: Backward Retrieval Vectors (Phi)
        self.retrieval_phi = jnp.zeros(
            (self.params.n_memory_slots, self.params.bitstream_length), dtype=jnp.uint8
        )
        # Index for cyclic imprinting
        self.current_slot = 0

    @staticmethod
    def _validate_positive_int(name: str, value: int) -> None:
        """Validate a strict positive integer configuration field."""
        if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
            raise ValueError(f"{name} must be a positive integer.")

    @classmethod
    def _validate_params(cls, params: L9_HolonomicParameters) -> None:
        """Validate Layer 9 parameters before allocating backend arrays."""
        cls._validate_positive_int("n_memory_slots", params.n_memory_slots)
        cls._validate_positive_int("bitstream_length", params.bitstream_length)
        cls._validate_positive_int("temporal_window", params.temporal_window)
        if not np.isfinite(params.retrieval_gain) or params.retrieval_gain < 0.0:
            raise ValueError("retrieval_gain must be finite and non-negative.")
        if not np.isfinite(params.weak_measurement_strength) or not (
            0.0 <= params.weak_measurement_strength <= 1.0
        ):
            raise ValueError("weak_measurement_strength must be finite and in [0, 1].")

    @staticmethod
    def _validate_dt(dt: float) -> None:
        """Validate a positive finite simulation timestep."""
        if not np.isfinite(dt) or dt <= 0.0:
            raise ValueError("dt must be finite and positive.")

    def _validate_input_batch(self, inputs: jnp.ndarray) -> jnp.ndarray:
        """Validate and normalise an upstream L9 bitstream batch."""
        input_batch: jnp.ndarray = jnp.asarray(inputs)
        if input_batch.ndim != 2:
            raise ValueError("inputs must be a rank-2 bitstream batch.")
        if input_batch.shape[0] <= 0:
            raise ValueError("inputs must contain at least one row.")
        if input_batch.shape[1] != self.params.bitstream_length:
            raise ValueError("inputs bitstream_length must match adapter parameters.")
        if not bool(np.all(np.isfinite(np.asarray(input_batch)))):
            raise ValueError("inputs must contain only finite values.")
        return input_batch

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """Map memory imprints to stochastic bitstreams via TSVF overlap.

        Parameters
        ----------
        domain_state:
            Reserved adapter payload for interface compatibility. Layer 9 uses
            internal TSVF state for encoding.

        Returns
        -------
        jnp.ndarray
            One-dimensional retrieved-memory bitstream with
            ``bitstream_length`` entries.
        """
        # Memory retrieval probability = Normalized overlap <Phi|Psi>
        psi_float = self.imprints_psi.astype(jnp.float32)
        phi_float = self.retrieval_phi.astype(jnp.float32)

        # Calculate overlap per slot
        overlap = jnp.mean(psi_float * phi_float, axis=1)
        # Sum overlaps to get retrieval activation
        retrieval_prob = jnp.clip(jnp.sum(overlap) * self.params.retrieval_gain, 0.0, 1.0)

        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.bitstream_length,))
        # Single channel output representing retrieved memory content
        bitstream: jnp.ndarray = (rands < retrieval_prob).astype(jnp.uint8)
        return bitstream

    @staticmethod
    @maybe_jit
    def _tsvf_kernel(
        psi: jnp.ndarray, phi: jnp.ndarray, inputs: jnp.ndarray, strength: float, dt: float
    ) -> Tuple[jnp.ndarray, jnp.ndarray]:
        """Update the forward and backward holographic imprints.

        Parameters
        ----------
        psi:
            Forward memory-imprint tensor.
        phi:
            Backward retrieval-vector tensor.
        inputs:
            Validated rank-2 upstream bitstream tensor.
        strength:
            Weak-measurement coupling reserved for the traced TSVF update.
        dt:
            Positive simulation timestep.

        Returns
        -------
        tuple[jnp.ndarray, jnp.ndarray]
            Updated ``psi`` and ``phi`` tensors.
        """
        # Forward imprinting Psi captures current input
        psi_next = jnp.where(inputs > 0.5, 1, psi).astype(jnp.uint8)
        # Backward retrieval Phi adapts to current state (Weak measurement)
        phi_next = jnp.where(jnp.abs(psi_next.astype(jnp.float32) - 0.5) > strength, 1, phi).astype(
            jnp.uint8
        )

        return psi_next, phi_next

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """Advance the L9 holonomic dynamics using JAX-compatible arrays.

        Parameters
        ----------
        dt:
            Positive finite simulation timestep.
        inputs:
            Optional ``(N, bitstream_length)`` upstream state to imprint. If
            ``N`` differs from ``n_memory_slots``, rows are tiled
            deterministically until all memory slots receive a row.

        Returns
        -------
        jnp.ndarray
            Retrieved-memory bitstream with shape ``(bitstream_length,)``.

        Raises
        ------
        ValueError
            If ``dt`` or ``inputs`` violates the bounded adapter contract.
        """
        self._validate_dt(dt)
        if inputs is not None:
            input_batch = self._validate_input_batch(inputs)
            # 1. Project inputs to memory slot count if necessary
            if input_batch.shape[0] != self.params.n_memory_slots:
                # Tile or truncate to match slots
                n_in = input_batch.shape[0]
                n_slots = self.params.n_memory_slots
                indices = jnp.arange(n_slots) % n_in
                mapped_inputs = input_batch[indices]
            else:
                mapped_inputs = input_batch

            # 2. Update forward/backward holographic imprints
            self.imprints_psi, self.retrieval_phi = self._tsvf_kernel(
                self.imprints_psi,
                self.retrieval_phi,
                mapped_inputs,
                self.params.weak_measurement_strength,
                dt,
            )

        # 3. Return retrieved bitstream (projected to node count)
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """Map bitstreams back to memory-retrieval quality.

        Parameters
        ----------
        bitstreams:
            Retrieved stochastic memory bitstream.

        Returns
        -------
        dict[str, float]
            Telemetry dictionary containing ``memory_retrieval_r9``.
        """
        return {"memory_retrieval_r9": float(jnp.mean(bitstreams.astype(jnp.float32)))}

    def get_metrics(self) -> Dict[str, float]:
        """Return L9-specific overlap and imprint-density metrics.

        Returns
        -------
        dict[str, float]
            Current holographic-overlap and imprint-density telemetry.
        """
        return {
            "holographic_overlap": float(
                jnp.mean(
                    self.imprints_psi.astype(jnp.float32) * self.retrieval_phi.astype(jnp.float32)
                )
            ),
            "imprint_density": float(jnp.mean(self.imprints_psi)),
        }

__init__(params=None, seed=49)

Initialise the Layer 9 memory adapter.

Parameters

params: Optional Layer 9 configuration. Defaults preserve the historical 64-slot, 1024-bitstream contract. seed: Random seed forwarded to the JAX or NumPy compatibility RNG.

Raises

ValueError If any parameter would create an invalid memory tensor or unsafe retrieval contract.

Source code in src/sc_neurocore/adapters/holonomic/l9_mem.py
Python
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def __init__(self, params: Optional[L9_HolonomicParameters] = None, seed: int = 49) -> None:
    """Initialise the Layer 9 memory adapter.

    Parameters
    ----------
    params:
        Optional Layer 9 configuration. Defaults preserve the historical
        64-slot, 1024-bitstream contract.
    seed:
        Random seed forwarded to the JAX or NumPy compatibility RNG.

    Raises
    ------
    ValueError
        If any parameter would create an invalid memory tensor or unsafe
        retrieval contract.
    """
    self.params = params or L9_HolonomicParameters()
    self._validate_params(self.params)
    self.rng_key = make_rng(seed)

    # State: Forward Bitstream Imprints (Psi)
    self.imprints_psi = jnp.zeros(
        (self.params.n_memory_slots, self.params.bitstream_length), dtype=jnp.uint8
    )
    # State: Backward Retrieval Vectors (Phi)
    self.retrieval_phi = jnp.zeros(
        (self.params.n_memory_slots, self.params.bitstream_length), dtype=jnp.uint8
    )
    # Index for cyclic imprinting
    self.current_slot = 0

encode(domain_state)

Map memory imprints to stochastic bitstreams via TSVF overlap.

Parameters

domain_state: Reserved adapter payload for interface compatibility. Layer 9 uses internal TSVF state for encoding.

Returns

jnp.ndarray One-dimensional retrieved-memory bitstream with bitstream_length entries.

Source code in src/sc_neurocore/adapters/holonomic/l9_mem.py
Python
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def encode(self, domain_state: Any) -> jnp.ndarray:
    """Map memory imprints to stochastic bitstreams via TSVF overlap.

    Parameters
    ----------
    domain_state:
        Reserved adapter payload for interface compatibility. Layer 9 uses
        internal TSVF state for encoding.

    Returns
    -------
    jnp.ndarray
        One-dimensional retrieved-memory bitstream with
        ``bitstream_length`` entries.
    """
    # Memory retrieval probability = Normalized overlap <Phi|Psi>
    psi_float = self.imprints_psi.astype(jnp.float32)
    phi_float = self.retrieval_phi.astype(jnp.float32)

    # Calculate overlap per slot
    overlap = jnp.mean(psi_float * phi_float, axis=1)
    # Sum overlaps to get retrieval activation
    retrieval_prob = jnp.clip(jnp.sum(overlap) * self.params.retrieval_gain, 0.0, 1.0)

    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.bitstream_length,))
    # Single channel output representing retrieved memory content
    bitstream: jnp.ndarray = (rands < retrieval_prob).astype(jnp.uint8)
    return bitstream

step_jax(dt, inputs=None)

Advance the L9 holonomic dynamics using JAX-compatible arrays.

Parameters

dt: Positive finite simulation timestep. inputs: Optional (N, bitstream_length) upstream state to imprint. If N differs from n_memory_slots, rows are tiled deterministically until all memory slots receive a row.

Returns

jnp.ndarray Retrieved-memory bitstream with shape (bitstream_length,).

Raises

ValueError If dt or inputs violates the bounded adapter contract.

Source code in src/sc_neurocore/adapters/holonomic/l9_mem.py
Python
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """Advance the L9 holonomic dynamics using JAX-compatible arrays.

    Parameters
    ----------
    dt:
        Positive finite simulation timestep.
    inputs:
        Optional ``(N, bitstream_length)`` upstream state to imprint. If
        ``N`` differs from ``n_memory_slots``, rows are tiled
        deterministically until all memory slots receive a row.

    Returns
    -------
    jnp.ndarray
        Retrieved-memory bitstream with shape ``(bitstream_length,)``.

    Raises
    ------
    ValueError
        If ``dt`` or ``inputs`` violates the bounded adapter contract.
    """
    self._validate_dt(dt)
    if inputs is not None:
        input_batch = self._validate_input_batch(inputs)
        # 1. Project inputs to memory slot count if necessary
        if input_batch.shape[0] != self.params.n_memory_slots:
            # Tile or truncate to match slots
            n_in = input_batch.shape[0]
            n_slots = self.params.n_memory_slots
            indices = jnp.arange(n_slots) % n_in
            mapped_inputs = input_batch[indices]
        else:
            mapped_inputs = input_batch

        # 2. Update forward/backward holographic imprints
        self.imprints_psi, self.retrieval_phi = self._tsvf_kernel(
            self.imprints_psi,
            self.retrieval_phi,
            mapped_inputs,
            self.params.weak_measurement_strength,
            dt,
        )

    # 3. Return retrieved bitstream (projected to node count)
    return self.encode(None)

decode(bitstreams)

Map bitstreams back to memory-retrieval quality.

Parameters

bitstreams: Retrieved stochastic memory bitstream.

Returns

dict[str, float] Telemetry dictionary containing memory_retrieval_r9.

Source code in src/sc_neurocore/adapters/holonomic/l9_mem.py
Python
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """Map bitstreams back to memory-retrieval quality.

    Parameters
    ----------
    bitstreams:
        Retrieved stochastic memory bitstream.

    Returns
    -------
    dict[str, float]
        Telemetry dictionary containing ``memory_retrieval_r9``.
    """
    return {"memory_retrieval_r9": float(jnp.mean(bitstreams.astype(jnp.float32)))}

get_metrics()

Return L9-specific overlap and imprint-density metrics.

Returns

dict[str, float] Current holographic-overlap and imprint-density telemetry.

Source code in src/sc_neurocore/adapters/holonomic/l9_mem.py
Python
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def get_metrics(self) -> Dict[str, float]:
    """Return L9-specific overlap and imprint-density metrics.

    Returns
    -------
    dict[str, float]
        Current holographic-overlap and imprint-density telemetry.
    """
    return {
        "holographic_overlap": float(
            jnp.mean(
                self.imprints_psi.astype(jnp.float32) * self.retrieval_phi.astype(jnp.float32)
            )
        ),
        "imprint_density": float(jnp.mean(self.imprints_psi)),
    }

L10_FirewallAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN Topological Firewall layer.

Source code in src/sc_neurocore/adapters/holonomic/l10_fire.py
Python
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
class L10_FirewallAdapter(BaseStochasticAdapter):
    """
    JAX-traceable adapter for the SCPN Topological Firewall layer.
    """

    def __init__(self, params: Optional[L10_HolonomicParameters] = None, seed: int = 410) -> None:
        self.params = params or L10_HolonomicParameters()

        self.rng_key = make_rng(seed)

        # State: Firewall integrity (0 to 1)
        self.firewall_strength = jnp.full((self.params.n_boundary_nodes,), 0.9)
        # State: Local Intention potential
        self.intention_potential = jnp.zeros((self.params.n_boundary_nodes,))

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """
        Maps firewall strength to stochastic bitstreams.
        """
        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_boundary_nodes, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < self.firewall_strength[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _firewall_kernel(
        strength: jnp.ndarray,
        intention: jnp.ndarray,
        noise_inputs: jnp.ndarray,
        gain: float,
        dt: float,
    ) -> Tuple[jnp.ndarray, jnp.ndarray]:
        """
        Solves the Firewall / Topological dynamics:
        dStrength/dt = -D_topo * Strength + Intention_Steering
        """
        # Dissonance is high when noise inputs don't match intention
        dissonance = jnp.abs(noise_inputs - intention)

        # Strength decays with dissonance, grows with steering
        d_strength = -dissonance * strength + gain * intention - 0.01 * strength
        strength_next = jnp.clip(strength + d_strength * dt, 0.0, 1.0)

        return strength_next, dissonance

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L10 holonomic dynamics using JAX.

        inputs: (n_boundary_nodes, bitstream_length) representing external noise or L14 signals.
        Returns: (n_boundary_nodes, bitstream_length) output bitstreams (Shielding signals).
        """
        # 1. Extract External Pressure (Inputs -> L10)
        if inputs is not None:
            external_noise = jnp.mean(inputs.astype(jnp.float32), axis=1)
            if external_noise.shape[0] != self.params.n_boundary_nodes:
                external_noise = jnp.full((self.params.n_boundary_nodes,), jnp.mean(external_noise))
        else:
            external_noise = jnp.zeros((self.params.n_boundary_nodes,))

        # 2. Execute Firewall Kernel
        self.firewall_strength, dissonance = self._firewall_kernel(
            self.firewall_strength,
            self.intention_potential,
            external_noise,
            self.params.steering_gain,
            dt,
        )

        # 3. Return encoded bitstreams (Shielding status)
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """
        Maps bitstreams back to Firewall Integrity index.
        """
        return {"firewall_integrity_r10": float(jnp.mean(bitstreams.astype(jnp.float32)))}

    def get_metrics(self) -> Dict[str, float]:
        """
        Returns L10-specific metrics.
        """
        return {
            "avg_shielding_potential": float(jnp.mean(self.firewall_strength)),
            "topological_dissonance": float(jnp.std(self.firewall_strength)),
        }

encode(domain_state)

Maps firewall strength to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l10_fire.py
Python
60
61
62
63
64
65
66
67
def encode(self, domain_state: Any) -> jnp.ndarray:
    """
    Maps firewall strength to stochastic bitstreams.
    """
    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_boundary_nodes, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < self.firewall_strength[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advances the L10 holonomic dynamics using JAX.

inputs: (n_boundary_nodes, bitstream_length) representing external noise or L14 signals. Returns: (n_boundary_nodes, bitstream_length) output bitstreams (Shielding signals).

Source code in src/sc_neurocore/adapters/holonomic/l10_fire.py
Python
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L10 holonomic dynamics using JAX.

    inputs: (n_boundary_nodes, bitstream_length) representing external noise or L14 signals.
    Returns: (n_boundary_nodes, bitstream_length) output bitstreams (Shielding signals).
    """
    # 1. Extract External Pressure (Inputs -> L10)
    if inputs is not None:
        external_noise = jnp.mean(inputs.astype(jnp.float32), axis=1)
        if external_noise.shape[0] != self.params.n_boundary_nodes:
            external_noise = jnp.full((self.params.n_boundary_nodes,), jnp.mean(external_noise))
    else:
        external_noise = jnp.zeros((self.params.n_boundary_nodes,))

    # 2. Execute Firewall Kernel
    self.firewall_strength, dissonance = self._firewall_kernel(
        self.firewall_strength,
        self.intention_potential,
        external_noise,
        self.params.steering_gain,
        dt,
    )

    # 3. Return encoded bitstreams (Shielding status)
    return self.encode(None)

decode(bitstreams)

Maps bitstreams back to Firewall Integrity index.

Source code in src/sc_neurocore/adapters/holonomic/l10_fire.py
Python
118
119
120
121
122
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """
    Maps bitstreams back to Firewall Integrity index.
    """
    return {"firewall_integrity_r10": float(jnp.mean(bitstreams.astype(jnp.float32)))}

get_metrics()

Returns L10-specific metrics.

Source code in src/sc_neurocore/adapters/holonomic/l10_fire.py
Python
124
125
126
127
128
129
130
131
def get_metrics(self) -> Dict[str, float]:
    """
    Returns L10-specific metrics.
    """
    return {
        "avg_shielding_potential": float(jnp.mean(self.firewall_strength)),
        "topological_dissonance": float(jnp.std(self.firewall_strength)),
    }

L11_NoosphericAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN Noospheric layer.

Source code in src/sc_neurocore/adapters/holonomic/l11_noos.py
Python
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
class L11_NoosphericAdapter(BaseStochasticAdapter):
    """
    JAX-traceable adapter for the SCPN Noospheric layer.
    """

    def __init__(self, params: Optional[L11_HolonomicParameters] = None, seed: int = 411) -> None:
        self.params = params or L11_HolonomicParameters()
        self.rng_key = make_rng(seed)

        # State: Cultural Spins (-1 to +1, represented as 0 to 1 probabilities)
        self.spins = jnp.full((self.params.n_nodes,), 0.5)
        # State: Information Density
        self.info_density = jnp.zeros((self.params.n_nodes,))

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """
        Maps cultural spins to stochastic bitstreams.
        """
        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_nodes, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < self.spins[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _nths_kernel(
        spins: jnp.ndarray, field_input: jnp.ndarray, j_avg: float, h_bias: float, dt: float
    ) -> jnp.ndarray:
        """
        Solves the NTHS Spin-Glass dynamics:
        dSpin/dt = J * MeanField + h_bias + field_input - decay
        """
        mean_field = jnp.mean(spins)
        # H = -J * s_i * sum(s_j) -> mapped to probability drift
        d_spin = j_avg * mean_field + h_bias + field_input - 0.1 * spins
        return jnp.clip(spins + d_spin * dt, 0.0, 1.0)

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L11 holonomic dynamics using JAX.

        inputs: (n_nodes, bitstream_length) representing L7 Symbolic or L10 Firewall signals.
        Returns: (n_nodes, bitstream_length) output bitstreams.
        """
        # 1. Extract Informational Forcing (L7/L10 -> L11)
        if inputs is not None:
            info_drive = jnp.mean(inputs.astype(jnp.float32), axis=1)
            # Map input dimensions
            if info_drive.shape[0] != self.params.n_nodes:
                info_drive = jnp.full((self.params.n_nodes,), jnp.mean(info_drive))
        else:
            info_drive = jnp.zeros((self.params.n_nodes,))

        # 2. Execute NTHS Kernel
        self.spins = self._nths_kernel(
            self.spins, info_drive, self.params.j_coupling, self.params.h_bias, dt
        )

        # 3. Update Information Density (Proxy for memetic SIR)
        self.info_density = 0.9 * self.info_density + 0.1 * jnp.abs(self.spins - 0.5)

        # 4. Return encoded bitstreams
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """
        Maps bitstreams back to Noospheric Polarization index.
        """
        spins = jnp.mean(bitstreams.astype(jnp.float32), axis=1)
        polarization = jnp.std(spins)
        return {
            "noospheric_polarization": float(polarization),
            "collective_coherence_r11": float(jnp.mean(spins)),
        }

    def get_metrics(self) -> Dict[str, float]:
        """
        Returns L11-specific metrics like Polarization and Info Density.
        """
        return {
            "avg_polarization": float(jnp.std(self.spins)),
            "noospheric_entropy": float(-jnp.sum(self.spins * jnp.log(self.spins + 1e-6))),
            "info_saturation": float(jnp.mean(self.info_density)),
        }

encode(domain_state)

Maps cultural spins to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l11_noos.py
Python
62
63
64
65
66
67
68
69
def encode(self, domain_state: Any) -> jnp.ndarray:
    """
    Maps cultural spins to stochastic bitstreams.
    """
    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_nodes, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < self.spins[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advances the L11 holonomic dynamics using JAX.

inputs: (n_nodes, bitstream_length) representing L7 Symbolic or L10 Firewall signals. Returns: (n_nodes, bitstream_length) output bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l11_noos.py
Python
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L11 holonomic dynamics using JAX.

    inputs: (n_nodes, bitstream_length) representing L7 Symbolic or L10 Firewall signals.
    Returns: (n_nodes, bitstream_length) output bitstreams.
    """
    # 1. Extract Informational Forcing (L7/L10 -> L11)
    if inputs is not None:
        info_drive = jnp.mean(inputs.astype(jnp.float32), axis=1)
        # Map input dimensions
        if info_drive.shape[0] != self.params.n_nodes:
            info_drive = jnp.full((self.params.n_nodes,), jnp.mean(info_drive))
    else:
        info_drive = jnp.zeros((self.params.n_nodes,))

    # 2. Execute NTHS Kernel
    self.spins = self._nths_kernel(
        self.spins, info_drive, self.params.j_coupling, self.params.h_bias, dt
    )

    # 3. Update Information Density (Proxy for memetic SIR)
    self.info_density = 0.9 * self.info_density + 0.1 * jnp.abs(self.spins - 0.5)

    # 4. Return encoded bitstreams
    return self.encode(None)

decode(bitstreams)

Maps bitstreams back to Noospheric Polarization index.

Source code in src/sc_neurocore/adapters/holonomic/l11_noos.py
Python
112
113
114
115
116
117
118
119
120
121
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """
    Maps bitstreams back to Noospheric Polarization index.
    """
    spins = jnp.mean(bitstreams.astype(jnp.float32), axis=1)
    polarization = jnp.std(spins)
    return {
        "noospheric_polarization": float(polarization),
        "collective_coherence_r11": float(jnp.mean(spins)),
    }

get_metrics()

Returns L11-specific metrics like Polarization and Info Density.

Source code in src/sc_neurocore/adapters/holonomic/l11_noos.py
Python
123
124
125
126
127
128
129
130
131
def get_metrics(self) -> Dict[str, float]:
    """
    Returns L11-specific metrics like Polarization and Info Density.
    """
    return {
        "avg_polarization": float(jnp.std(self.spins)),
        "noospheric_entropy": float(-jnp.sum(self.spins * jnp.log(self.spins + 1e-6))),
        "info_saturation": float(jnp.mean(self.info_density)),
    }

L12_GaianAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN Ecological-Gaian layer.

Source code in src/sc_neurocore/adapters/holonomic/l12_gaian.py
Python
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
class L12_GaianAdapter(BaseStochasticAdapter):
    """
    JAX-traceable adapter for the SCPN Ecological-Gaian layer.
    """

    def __init__(self, params: Optional[L12_HolonomicParameters] = None, seed: int = 412) -> None:
        self.params = params or L12_HolonomicParameters()
        self.rng_key = make_rng(seed)

        # State: Ecological Coherence (0 to 1)
        self.eco_coherence = jnp.full((self.params.n_nodes,), 0.2)
        # State: Nutrient/Information Flow density
        self.flow_density = jnp.zeros((self.params.n_nodes,))
        # State: Environmental Phase
        self.env_phase = 0.0

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """
        Maps ecological coherence to stochastic bitstreams.
        """
        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_nodes, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < self.eco_coherence[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _enaqt_kernel(
        coherence: jnp.ndarray, flow: jnp.ndarray, j_coupling: float, noise_gain: float, dt: float
    ) -> Tuple[jnp.ndarray, jnp.ndarray]:
        """
        Solves the ENAQT transport dynamics:
        dC/dt = J * noise * (1 - C) - decay
        """
        # Noise-assisted transport increases coherence
        d_coherence = j_coupling * noise_gain * (1.0 - coherence) - 0.05 * coherence
        coherence_next = jnp.clip(coherence + d_coherence * dt, 0.0, 1.0)

        # Flow density is proportional to coherence gradients
        new_flow = coherence_next * 0.5

        return coherence_next, new_flow

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L12 holonomic dynamics using JAX.

        inputs: (n_nodes, bitstream_length) representing L6 Planetary or L11 Noospheric drive.
        Returns: (n_nodes, bitstream_length) output bitstreams.
        """
        self.env_phase += self.params.solar_lunar_omega * dt

        # 1. Extract Environmental Forcing (L6/L11 -> L12)
        if inputs is not None:
            raw_input = jnp.mean(inputs.astype(jnp.float32), axis=1)
            # Map input dimensions
            if raw_input.shape[0] != self.params.n_nodes:
                env_drive = jnp.full((self.params.n_nodes,), jnp.mean(raw_input))
            else:
                env_drive = raw_input
        else:
            env_drive = jnp.zeros((self.params.n_nodes,))

        # 2. Execute ENAQT Kernel
        # Incorporate environmental drive into noise-assistance
        effective_noise = self.params.noise_assistance_factor * (1.0 + env_drive)
        self.eco_coherence, self.flow_density = self._enaqt_kernel(
            self.eco_coherence,
            self.flow_density,
            self.params.j_coherent_coupling,
            jnp.mean(effective_noise),
            dt,
        )

        # 3. Return encoded bitstreams
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """
        Maps bitstreams back to Gaian Synchrony Index.
        """
        return {
            "gaian_synchrony_index": float(jnp.mean(bitstreams.astype(jnp.float32))),
            "mycorrhizal_flow_rate": float(jnp.mean(self.flow_density)),
        }

    def get_metrics(self) -> Dict[str, float]:
        """
        Returns L12-specific metrics like Coherence and Flow.
        """
        return {
            "eco_system_coherence": float(jnp.mean(self.eco_coherence)),
            "global_nutrient_flow": float(jnp.mean(self.flow_density)),
            "environmental_alignment": float(jnp.sin(self.env_phase)),
        }

encode(domain_state)

Maps ecological coherence to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l12_gaian.py
Python
64
65
66
67
68
69
70
71
def encode(self, domain_state: Any) -> jnp.ndarray:
    """
    Maps ecological coherence to stochastic bitstreams.
    """
    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_nodes, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < self.eco_coherence[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advances the L12 holonomic dynamics using JAX.

inputs: (n_nodes, bitstream_length) representing L6 Planetary or L11 Noospheric drive. Returns: (n_nodes, bitstream_length) output bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l12_gaian.py
Python
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L12 holonomic dynamics using JAX.

    inputs: (n_nodes, bitstream_length) representing L6 Planetary or L11 Noospheric drive.
    Returns: (n_nodes, bitstream_length) output bitstreams.
    """
    self.env_phase += self.params.solar_lunar_omega * dt

    # 1. Extract Environmental Forcing (L6/L11 -> L12)
    if inputs is not None:
        raw_input = jnp.mean(inputs.astype(jnp.float32), axis=1)
        # Map input dimensions
        if raw_input.shape[0] != self.params.n_nodes:
            env_drive = jnp.full((self.params.n_nodes,), jnp.mean(raw_input))
        else:
            env_drive = raw_input
    else:
        env_drive = jnp.zeros((self.params.n_nodes,))

    # 2. Execute ENAQT Kernel
    # Incorporate environmental drive into noise-assistance
    effective_noise = self.params.noise_assistance_factor * (1.0 + env_drive)
    self.eco_coherence, self.flow_density = self._enaqt_kernel(
        self.eco_coherence,
        self.flow_density,
        self.params.j_coherent_coupling,
        jnp.mean(effective_noise),
        dt,
    )

    # 3. Return encoded bitstreams
    return self.encode(None)

decode(bitstreams)

Maps bitstreams back to Gaian Synchrony Index.

Source code in src/sc_neurocore/adapters/holonomic/l12_gaian.py
Python
125
126
127
128
129
130
131
132
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """
    Maps bitstreams back to Gaian Synchrony Index.
    """
    return {
        "gaian_synchrony_index": float(jnp.mean(bitstreams.astype(jnp.float32))),
        "mycorrhizal_flow_rate": float(jnp.mean(self.flow_density)),
    }

get_metrics()

Returns L12-specific metrics like Coherence and Flow.

Source code in src/sc_neurocore/adapters/holonomic/l12_gaian.py
Python
134
135
136
137
138
139
140
141
142
def get_metrics(self) -> Dict[str, float]:
    """
    Returns L12-specific metrics like Coherence and Flow.
    """
    return {
        "eco_system_coherence": float(jnp.mean(self.eco_coherence)),
        "global_nutrient_flow": float(jnp.mean(self.flow_density)),
        "environmental_alignment": float(jnp.sin(self.env_phase)),
    }

L13_SourceAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN source-field layer.

Source code in src/sc_neurocore/adapters/holonomic/l13_source.py
Python
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
class L13_SourceAdapter(BaseStochasticAdapter):
    """JAX-traceable adapter for the SCPN source-field layer."""

    def __init__(self, params: Optional[L13_HolonomicParameters] = None, seed: int = 413) -> None:
        """Initialise the Layer 13 source-field adapter.

        Parameters
        ----------
        params:
            Optional vacuum-lattice configuration. Defaults preserve the
            historical 256-node, 1024-bitstream contract.
        seed:
            Random seed forwarded to the JAX or NumPy compatibility RNG.

        Raises
        ------
        ValueError
            If configuration values cannot produce finite bounded dynamics.
        """
        self.params = params or L13_HolonomicParameters()
        self._validate_params(self.params)
        self.rng_key = make_rng(seed)

        # State: Vacuum Potential (0.0 to 1.0)
        self.vacuum_state = jnp.full((self.params.n_vacuum_nodes,), 0.5)
        if self.params.lambda_scission > 0.0:
            self.rng_key, subkey = split_rng(self.rng_key)
            amplitude = min(float(self.params.lambda_scission), 1.0) * 0.02
            perturbation = (uniform(subkey, (self.params.n_vacuum_nodes,)) - 0.5) * amplitude
            self.vacuum_state = jnp.clip(self.vacuum_state + perturbation, 0.0, 1.0)
        # State: Fisher Information Metric Density
        self.fim_density = jnp.zeros((self.params.n_vacuum_nodes,))

    @staticmethod
    def _validate_positive_int(name: str, value: int) -> None:
        """Validate a strict positive integer configuration field."""
        if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
            raise ValueError(f"{name} must be a positive integer.")

    @classmethod
    def _validate_params(cls, params: L13_HolonomicParameters) -> None:
        """Validate Layer 13 parameters before allocating backend arrays."""
        cls._validate_positive_int("n_vacuum_nodes", params.n_vacuum_nodes)
        cls._validate_positive_int("bitstream_length", params.bitstream_length)

        if not np.isfinite(params.j_primordial_coupling):
            raise ValueError("j_primordial_coupling must be finite.")
        if not np.isfinite(params.h_potential_bias):
            raise ValueError("h_potential_bias must be finite.")
        if not np.isfinite(params.lambda_scission) or params.lambda_scission < 0.0:
            raise ValueError("lambda_scission must be finite and non-negative.")

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """Map vacuum potential to stochastic source-field bitstreams.

        Parameters
        ----------
        domain_state:
            Reserved adapter payload for interface compatibility. Layer 13 uses
            its internal vacuum lattice state for encoding.

        Returns
        -------
        jnp.ndarray
            Rank-2 bitstream matrix with shape
            ``(n_vacuum_nodes, bitstream_length)``.
        """
        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_vacuum_nodes, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < self.vacuum_state[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _vacuum_lattice_kernel(
        state: jnp.ndarray,
        coupling: float,
        bias: float,
        scission_rate: float,
        feedback_drive: jnp.ndarray,
        dt: float,
    ) -> jnp.ndarray:
        """Advance local spin-like vacuum lattice dynamics.

        Parameters
        ----------
        state:
            Current bounded vacuum potential vector.
        coupling:
            Finite nearest-neighbour primordial lattice coupling.
        bias:
            Finite scalar source-field bias.
        scission_rate:
            Non-negative symmetry-breaking drive.
        feedback_drive:
            Bounded L16 cybernetic-closure feedback vector in ``[-1, 1]``.
        dt:
            Positive finite simulation timestep.

        Returns
        -------
        jnp.ndarray
            Updated bounded vacuum potential vector.
        """
        spin = 2.0 * jnp.clip(state, 0.0, 1.0) - 1.0
        neighbour_field = 0.5 * (jnp.roll(spin, -1) + jnp.roll(spin, 1))
        hamiltonian_drive = coupling * neighbour_field + bias + 0.25 * feedback_drive
        scission_drive = scission_rate * (spin - spin * spin * spin)
        relaxation = -0.05 * spin
        spin_next = spin + (hamiltonian_drive + scission_drive + relaxation) * dt
        return jnp.clip(0.5 * (spin_next + 1.0), 0.0, 1.0)

    @staticmethod
    def _validate_dt(dt: float) -> None:
        """Validate a positive finite simulation timestep."""
        if not np.isfinite(dt) or dt <= 0.0:
            raise ValueError("dt must be finite and positive.")

    def _project_feedback(self, inputs: Optional[jnp.ndarray]) -> jnp.ndarray:
        """Project optional L16 feedback onto the configured vacuum lattice."""
        if inputs is None:
            return jnp.zeros((self.params.n_vacuum_nodes,))

        feedback = jnp.asarray(inputs)
        raw_inputs = np.asarray(feedback, dtype=float)
        if raw_inputs.ndim > 2:
            raise ValueError("inputs must have rank 0, 1, or 2.")
        if raw_inputs.ndim == 1 and raw_inputs.shape[0] == 0:
            raise ValueError("inputs must contain at least one value.")
        if raw_inputs.ndim == 2:
            if raw_inputs.shape[0] == 0:
                raise ValueError("inputs must contain at least one row.")
            if raw_inputs.shape[1] == 0:
                raise ValueError("inputs must contain at least one column.")
        if not np.all(np.isfinite(raw_inputs)):
            raise ValueError("inputs must contain only finite values.")

        if feedback.ndim == 0:
            raw = jnp.full((self.params.n_vacuum_nodes,), feedback)
        elif feedback.ndim == 1:
            raw = feedback.astype(jnp.float32)
        else:
            raw = jnp.mean(feedback.astype(jnp.float32), axis=1)

        if raw.shape[0] != self.params.n_vacuum_nodes:
            raw = jnp.full((self.params.n_vacuum_nodes,), jnp.mean(raw))
        return jnp.clip(2.0 * raw - 1.0, -1.0, 1.0)

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """Advance the L13 holonomic dynamics using JAX-compatible arrays.

        Parameters
        ----------
        dt:
            Positive finite simulation timestep.
        inputs:
            Optional L16 cybernetic-closure feedback. Scalars broadcast across
            all nodes, rank-1 arrays map directly or broadcast by their mean
            when length differs, and rank-2 batches collapse by row mean before
            the same node-count projection.

        Returns
        -------
        jnp.ndarray
            Output bitstreams with shape ``(n_vacuum_nodes, bitstream_length)``.

        Raises
        ------
        ValueError
            If ``dt`` or ``inputs`` violates the bounded adapter contract.
        """
        self._validate_dt(dt)

        previous_state = self.vacuum_state
        feedback_drive = self._project_feedback(inputs)

        # 1. Update Vacuum State
        self.vacuum_state = self._vacuum_lattice_kernel(
            self.vacuum_state,
            self.params.j_primordial_coupling,
            self.params.h_potential_bias,
            self.params.lambda_scission,
            feedback_drive,
            dt,
        )

        # 2. Update FIM Density (Measures rate of change / information work)
        # Bernoulli-local Fisher density from temporal and lattice gradients.
        variance = jnp.clip(self.vacuum_state * (1.0 - self.vacuum_state), 1e-6, None)
        temporal_delta = self.vacuum_state - previous_state
        lattice_delta = jnp.roll(self.vacuum_state, -1) - self.vacuum_state
        instant_fim = (temporal_delta * temporal_delta + lattice_delta * lattice_delta) / variance
        self.fim_density = 0.9 * self.fim_density + 0.1 * instant_fim

        # 3. Return encoded bitstreams (The primordial carrier)
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """Map bitstreams back to primordial source coherence.

        Parameters
        ----------
        bitstreams:
            Source-field stochastic bitstream matrix.

        Returns
        -------
        dict[str, float]
            Telemetry dictionary containing ``source_coherence_r13``.

        Raises
        ------
        ValueError
            If ``bitstreams`` is not a finite non-empty rank-2 matrix.
        """
        bitstream_batch: jnp.ndarray = jnp.asarray(bitstreams)
        raw_bitstreams = np.asarray(bitstream_batch, dtype=float)
        if raw_bitstreams.ndim != 2:
            raise ValueError("bitstreams must be a rank-2 matrix.")
        if raw_bitstreams.shape[0] == 0 or raw_bitstreams.shape[1] == 0:
            raise ValueError("bitstreams must be a non-empty matrix.")
        if not np.all(np.isfinite(raw_bitstreams)):
            raise ValueError("bitstreams must contain only finite values.")
        return {"source_coherence_r13": float(jnp.mean(bitstream_batch.astype(jnp.float32)))}

    def get_metrics(self) -> Dict[str, float]:
        """Return L13-specific vacuum and Fisher-metric telemetry.

        Returns
        -------
        dict[str, float]
            Current vacuum potential and Fisher information metric density.
        """
        return {
            "vacuum_potential": float(jnp.mean(self.vacuum_state)),
            "fisher_information_metric": float(jnp.mean(self.fim_density)),
        }

__init__(params=None, seed=413)

Initialise the Layer 13 source-field adapter.

Parameters

params: Optional vacuum-lattice configuration. Defaults preserve the historical 256-node, 1024-bitstream contract. seed: Random seed forwarded to the JAX or NumPy compatibility RNG.

Raises

ValueError If configuration values cannot produce finite bounded dynamics.

Source code in src/sc_neurocore/adapters/holonomic/l13_source.py
Python
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(self, params: Optional[L13_HolonomicParameters] = None, seed: int = 413) -> None:
    """Initialise the Layer 13 source-field adapter.

    Parameters
    ----------
    params:
        Optional vacuum-lattice configuration. Defaults preserve the
        historical 256-node, 1024-bitstream contract.
    seed:
        Random seed forwarded to the JAX or NumPy compatibility RNG.

    Raises
    ------
    ValueError
        If configuration values cannot produce finite bounded dynamics.
    """
    self.params = params or L13_HolonomicParameters()
    self._validate_params(self.params)
    self.rng_key = make_rng(seed)

    # State: Vacuum Potential (0.0 to 1.0)
    self.vacuum_state = jnp.full((self.params.n_vacuum_nodes,), 0.5)
    if self.params.lambda_scission > 0.0:
        self.rng_key, subkey = split_rng(self.rng_key)
        amplitude = min(float(self.params.lambda_scission), 1.0) * 0.02
        perturbation = (uniform(subkey, (self.params.n_vacuum_nodes,)) - 0.5) * amplitude
        self.vacuum_state = jnp.clip(self.vacuum_state + perturbation, 0.0, 1.0)
    # State: Fisher Information Metric Density
    self.fim_density = jnp.zeros((self.params.n_vacuum_nodes,))

encode(domain_state)

Map vacuum potential to stochastic source-field bitstreams.

Parameters

domain_state: Reserved adapter payload for interface compatibility. Layer 13 uses its internal vacuum lattice state for encoding.

Returns

jnp.ndarray Rank-2 bitstream matrix with shape (n_vacuum_nodes, bitstream_length).

Source code in src/sc_neurocore/adapters/holonomic/l13_source.py
Python
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def encode(self, domain_state: Any) -> jnp.ndarray:
    """Map vacuum potential to stochastic source-field bitstreams.

    Parameters
    ----------
    domain_state:
        Reserved adapter payload for interface compatibility. Layer 13 uses
        its internal vacuum lattice state for encoding.

    Returns
    -------
    jnp.ndarray
        Rank-2 bitstream matrix with shape
        ``(n_vacuum_nodes, bitstream_length)``.
    """
    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_vacuum_nodes, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < self.vacuum_state[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advance the L13 holonomic dynamics using JAX-compatible arrays.

Parameters

dt: Positive finite simulation timestep. inputs: Optional L16 cybernetic-closure feedback. Scalars broadcast across all nodes, rank-1 arrays map directly or broadcast by their mean when length differs, and rank-2 batches collapse by row mean before the same node-count projection.

Returns

jnp.ndarray Output bitstreams with shape (n_vacuum_nodes, bitstream_length).

Raises

ValueError If dt or inputs violates the bounded adapter contract.

Source code in src/sc_neurocore/adapters/holonomic/l13_source.py
Python
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """Advance the L13 holonomic dynamics using JAX-compatible arrays.

    Parameters
    ----------
    dt:
        Positive finite simulation timestep.
    inputs:
        Optional L16 cybernetic-closure feedback. Scalars broadcast across
        all nodes, rank-1 arrays map directly or broadcast by their mean
        when length differs, and rank-2 batches collapse by row mean before
        the same node-count projection.

    Returns
    -------
    jnp.ndarray
        Output bitstreams with shape ``(n_vacuum_nodes, bitstream_length)``.

    Raises
    ------
    ValueError
        If ``dt`` or ``inputs`` violates the bounded adapter contract.
    """
    self._validate_dt(dt)

    previous_state = self.vacuum_state
    feedback_drive = self._project_feedback(inputs)

    # 1. Update Vacuum State
    self.vacuum_state = self._vacuum_lattice_kernel(
        self.vacuum_state,
        self.params.j_primordial_coupling,
        self.params.h_potential_bias,
        self.params.lambda_scission,
        feedback_drive,
        dt,
    )

    # 2. Update FIM Density (Measures rate of change / information work)
    # Bernoulli-local Fisher density from temporal and lattice gradients.
    variance = jnp.clip(self.vacuum_state * (1.0 - self.vacuum_state), 1e-6, None)
    temporal_delta = self.vacuum_state - previous_state
    lattice_delta = jnp.roll(self.vacuum_state, -1) - self.vacuum_state
    instant_fim = (temporal_delta * temporal_delta + lattice_delta * lattice_delta) / variance
    self.fim_density = 0.9 * self.fim_density + 0.1 * instant_fim

    # 3. Return encoded bitstreams (The primordial carrier)
    return self.encode(None)

decode(bitstreams)

Map bitstreams back to primordial source coherence.

Parameters

bitstreams: Source-field stochastic bitstream matrix.

Returns

dict[str, float] Telemetry dictionary containing source_coherence_r13.

Raises

ValueError If bitstreams is not a finite non-empty rank-2 matrix.

Source code in src/sc_neurocore/adapters/holonomic/l13_source.py
Python
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """Map bitstreams back to primordial source coherence.

    Parameters
    ----------
    bitstreams:
        Source-field stochastic bitstream matrix.

    Returns
    -------
    dict[str, float]
        Telemetry dictionary containing ``source_coherence_r13``.

    Raises
    ------
    ValueError
        If ``bitstreams`` is not a finite non-empty rank-2 matrix.
    """
    bitstream_batch: jnp.ndarray = jnp.asarray(bitstreams)
    raw_bitstreams = np.asarray(bitstream_batch, dtype=float)
    if raw_bitstreams.ndim != 2:
        raise ValueError("bitstreams must be a rank-2 matrix.")
    if raw_bitstreams.shape[0] == 0 or raw_bitstreams.shape[1] == 0:
        raise ValueError("bitstreams must be a non-empty matrix.")
    if not np.all(np.isfinite(raw_bitstreams)):
        raise ValueError("bitstreams must contain only finite values.")
    return {"source_coherence_r13": float(jnp.mean(bitstream_batch.astype(jnp.float32)))}

get_metrics()

Return L13-specific vacuum and Fisher-metric telemetry.

Returns

dict[str, float] Current vacuum potential and Fisher information metric density.

Source code in src/sc_neurocore/adapters/holonomic/l13_source.py
Python
284
285
286
287
288
289
290
291
292
293
294
295
def get_metrics(self) -> Dict[str, float]:
    """Return L13-specific vacuum and Fisher-metric telemetry.

    Returns
    -------
    dict[str, float]
        Current vacuum potential and Fisher information metric density.
    """
    return {
        "vacuum_potential": float(jnp.mean(self.vacuum_state)),
        "fisher_information_metric": float(jnp.mean(self.fim_density)),
    }

L14_TransdimensionalAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN Transdimensional layer.

Source code in src/sc_neurocore/adapters/holonomic/l14_trans.py
Python
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class L14_TransdimensionalAdapter(BaseStochasticAdapter):
    """
    JAX-traceable adapter for the SCPN Transdimensional layer.
    """

    def __init__(self, params: Optional[L14_HolonomicParameters] = None, seed: int = 414) -> None:
        self.params = params or L14_HolonomicParameters()
        self.rng_key = make_rng(seed)

        # State: Brane Alignment (0.0 to 1.0)
        self.brane_alignment = jnp.zeros((self.params.n_bulk_dimensions,))
        # State: Resonance Intensity
        self.resonance_intensity = jnp.zeros((self.params.n_bulk_dimensions,))

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """
        Maps resonance alignment to stochastic bitstreams.
        """
        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_bulk_dimensions, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < self.brane_alignment[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _resonance_kernel(
        alignment: jnp.ndarray, pta_input: jnp.ndarray, keystone_f: float, dt: float
    ) -> Tuple[jnp.ndarray, jnp.ndarray]:
        """
        Solves the Inter-brane Resonance dynamics:
        dAlignment/dt = overlap(PTA, Keystone) * coupling - dissipation
        """
        # Alignment increases when inputs match the keystone frequency proxy
        # Here we use input coherence as a proxy for frequency alignment
        d_align = 0.1 * pta_input - 0.02 * alignment
        alignment_next = jnp.clip(alignment + d_align * dt, 0.0, 1.0)

        # Intensity maps to the sharpness of the peak
        intensity = jnp.exp(-jnp.abs(alignment_next - 1.0) / 0.1)

        return alignment_next, intensity

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L14 holonomic dynamics using JAX.

        inputs: (N, bitstream_length) representing L8 Cosmic PTA signals.
        Returns: (n_bulk_dimensions, bitstream_length) output bitstreams.
        """
        # 1. Extract Cosmic Clock Reference (L8 -> L14)
        if inputs is not None:
            clock_ref = jnp.mean(inputs.astype(jnp.float32), axis=1)
            if clock_ref.shape[0] != self.params.n_bulk_dimensions:
                clock_ref = jnp.full((self.params.n_bulk_dimensions,), jnp.mean(clock_ref))
        else:
            clock_ref = jnp.zeros((self.params.n_bulk_dimensions,))

        # 2. Execute Resonance Kernel
        self.brane_alignment, self.resonance_intensity = self._resonance_kernel(
            self.brane_alignment, clock_ref, self.params.keystone_frequency, dt
        )

        # 3. Return encoded bitstreams (The transdimensional broadcast)
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """
        Maps bitstreams back to Brane Alignment index.
        """
        return {"brane_resonance_r14": float(jnp.mean(bitstreams.astype(jnp.float32)))}

    def get_metrics(self) -> Dict[str, float]:
        """
        Returns L14-specific metrics.
        """
        return {
            "avg_brane_alignment": float(jnp.mean(self.brane_alignment)),
            "resonance_sharpness": float(jnp.mean(self.resonance_intensity)),
        }

encode(domain_state)

Maps resonance alignment to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l14_trans.py
Python
59
60
61
62
63
64
65
66
def encode(self, domain_state: Any) -> jnp.ndarray:
    """
    Maps resonance alignment to stochastic bitstreams.
    """
    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_bulk_dimensions, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < self.brane_alignment[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advances the L14 holonomic dynamics using JAX.

inputs: (N, bitstream_length) representing L8 Cosmic PTA signals. Returns: (n_bulk_dimensions, bitstream_length) output bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l14_trans.py
Python
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L14 holonomic dynamics using JAX.

    inputs: (N, bitstream_length) representing L8 Cosmic PTA signals.
    Returns: (n_bulk_dimensions, bitstream_length) output bitstreams.
    """
    # 1. Extract Cosmic Clock Reference (L8 -> L14)
    if inputs is not None:
        clock_ref = jnp.mean(inputs.astype(jnp.float32), axis=1)
        if clock_ref.shape[0] != self.params.n_bulk_dimensions:
            clock_ref = jnp.full((self.params.n_bulk_dimensions,), jnp.mean(clock_ref))
    else:
        clock_ref = jnp.zeros((self.params.n_bulk_dimensions,))

    # 2. Execute Resonance Kernel
    self.brane_alignment, self.resonance_intensity = self._resonance_kernel(
        self.brane_alignment, clock_ref, self.params.keystone_frequency, dt
    )

    # 3. Return encoded bitstreams (The transdimensional broadcast)
    return self.encode(None)

decode(bitstreams)

Maps bitstreams back to Brane Alignment index.

Source code in src/sc_neurocore/adapters/holonomic/l14_trans.py
Python
110
111
112
113
114
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """
    Maps bitstreams back to Brane Alignment index.
    """
    return {"brane_resonance_r14": float(jnp.mean(bitstreams.astype(jnp.float32)))}

get_metrics()

Returns L14-specific metrics.

Source code in src/sc_neurocore/adapters/holonomic/l14_trans.py
Python
116
117
118
119
120
121
122
123
def get_metrics(self) -> Dict[str, float]:
    """
    Returns L14-specific metrics.
    """
    return {
        "avg_brane_alignment": float(jnp.mean(self.brane_alignment)),
        "resonance_sharpness": float(jnp.mean(self.resonance_intensity)),
    }

L15_ConsiliumAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN Consilium layer.

Source code in src/sc_neurocore/adapters/holonomic/l15_cons.py
Python
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
class L15_ConsiliumAdapter(BaseStochasticAdapter):
    """
    JAX-traceable adapter for the SCPN Consilium layer.
    """

    def __init__(self, params: Optional[L15_HolonomicParameters] = None, seed: int = 415) -> None:
        self.params = params or L15_HolonomicParameters()
        self.rng_key = make_rng(seed)

        # State: Universal Metric (Vector of layer weights)
        self.universal_metric = jnp.full(
            (self.params.n_metric_dimensions,), 1.0 / self.params.n_metric_dimensions
        )
        # State: Global Coherence Index (GCI)
        self.gci = 0.5
        # State: Collective Attractor Position
        self.attractor_pos = jnp.zeros((self.params.n_metric_dimensions,))

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """
        Maps executive optimization state to stochastic bitstreams.
        """
        # GCI mapped to bitstream density
        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_metric_dimensions, self.params.bitstream_length))
        bitstreams: jnp.ndarray = (rands < self.universal_metric[:, None] * self.gci * 10.0).astype(
            jnp.uint8
        )
        return bitstreams

    @staticmethod
    @maybe_jit
    def _umo_kernel(
        metric: jnp.ndarray, layer_coherences: jnp.ndarray, target: float, lr: float, dt: float
    ) -> Tuple[jnp.ndarray, jnp.ndarray]:
        """
        Solves the UMO / SEC optimization:
        dMetric/dt = (Target - Coherence) * grad(Surprise)
        """
        # Calculate global coherence proxy
        gci_next = jnp.mean(layer_coherences)

        # Adjust metric weights toward the target attractor
        error = target - gci_next
        d_metric = lr * error * layer_coherences - 0.01 * metric
        metric_next = jnp.clip(metric + d_metric * dt, 0.0, 1.0)
        # Normalize weights
        metric_next = metric_next / (jnp.sum(metric_next) + 1e-6)

        return metric_next, gci_next

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L15 holonomic dynamics using JAX.

        inputs: (16, bitstream_length) representing coherences of all 16 layers.
        Returns: (16, bitstream_length) output bitstreams (Executive steering).
        """
        # 1. Extract Layer Coherences (The full stack feedback)
        if inputs is not None:
            layer_syncs = jnp.mean(inputs.astype(jnp.float32), axis=1)
            # Map input dimensions if partial stack
            if layer_syncs.shape[0] != self.params.n_metric_dimensions:
                layer_syncs = jnp.pad(
                    layer_syncs, (0, self.params.n_metric_dimensions - layer_syncs.shape[0])
                )
        else:
            layer_syncs = jnp.zeros((self.params.n_metric_dimensions,))

        # 2. Execute UMO Kernel
        self.universal_metric, self.gci = self._umo_kernel(
            self.universal_metric,
            layer_syncs,
            self.params.coherence_target,
            self.params.learning_rate,
            dt,
        )

        # 3. Return encoded bitstreams (The executive steering signal)
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """
        Maps bitstreams back to Global Coherence Index.
        """
        return {"global_coherence_r15": float(self.gci)}

    def get_metrics(self) -> Dict[str, float]:
        """
        Returns L15-specific metrics.
        """
        return {
            "gci_index": float(self.gci),
            "metric_entropy": float(
                -jnp.sum(self.universal_metric * jnp.log(self.universal_metric + 1e-6))
            ),
            "optimizer_error": float(self.params.coherence_target - self.gci),
        }

encode(domain_state)

Maps executive optimization state to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l15_cons.py
Python
63
64
65
66
67
68
69
70
71
72
73
def encode(self, domain_state: Any) -> jnp.ndarray:
    """
    Maps executive optimization state to stochastic bitstreams.
    """
    # GCI mapped to bitstream density
    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_metric_dimensions, self.params.bitstream_length))
    bitstreams: jnp.ndarray = (rands < self.universal_metric[:, None] * self.gci * 10.0).astype(
        jnp.uint8
    )
    return bitstreams

step_jax(dt, inputs=None)

Advances the L15 holonomic dynamics using JAX.

inputs: (16, bitstream_length) representing coherences of all 16 layers. Returns: (16, bitstream_length) output bitstreams (Executive steering).

Source code in src/sc_neurocore/adapters/holonomic/l15_cons.py
Python
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L15 holonomic dynamics using JAX.

    inputs: (16, bitstream_length) representing coherences of all 16 layers.
    Returns: (16, bitstream_length) output bitstreams (Executive steering).
    """
    # 1. Extract Layer Coherences (The full stack feedback)
    if inputs is not None:
        layer_syncs = jnp.mean(inputs.astype(jnp.float32), axis=1)
        # Map input dimensions if partial stack
        if layer_syncs.shape[0] != self.params.n_metric_dimensions:
            layer_syncs = jnp.pad(
                layer_syncs, (0, self.params.n_metric_dimensions - layer_syncs.shape[0])
            )
    else:
        layer_syncs = jnp.zeros((self.params.n_metric_dimensions,))

    # 2. Execute UMO Kernel
    self.universal_metric, self.gci = self._umo_kernel(
        self.universal_metric,
        layer_syncs,
        self.params.coherence_target,
        self.params.learning_rate,
        dt,
    )

    # 3. Return encoded bitstreams (The executive steering signal)
    return self.encode(None)

decode(bitstreams)

Maps bitstreams back to Global Coherence Index.

Source code in src/sc_neurocore/adapters/holonomic/l15_cons.py
Python
126
127
128
129
130
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """
    Maps bitstreams back to Global Coherence Index.
    """
    return {"global_coherence_r15": float(self.gci)}

get_metrics()

Returns L15-specific metrics.

Source code in src/sc_neurocore/adapters/holonomic/l15_cons.py
Python
132
133
134
135
136
137
138
139
140
141
142
def get_metrics(self) -> Dict[str, float]:
    """
    Returns L15-specific metrics.
    """
    return {
        "gci_index": float(self.gci),
        "metric_entropy": float(
            -jnp.sum(self.universal_metric * jnp.log(self.universal_metric + 1e-6))
        ),
        "optimizer_error": float(self.params.coherence_target - self.gci),
    }

L16_MetaAdapter

Bases: BaseStochasticAdapter

JAX-traceable adapter for the SCPN Cybernetic Closure layer (The Director).

Source code in src/sc_neurocore/adapters/holonomic/l16_meta.py
Python
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
class L16_MetaAdapter(BaseStochasticAdapter):
    """
    JAX-traceable adapter for the SCPN Cybernetic Closure layer (The Director).
    """

    def __init__(self, params: Optional[L16_HolonomicParameters] = None, seed: int = 416) -> None:
        self.params = params or L16_HolonomicParameters()
        self.rng_key = make_rng(seed)

        # State: Director's Will (0.0 to 1.0)
        self.meta_will = jnp.full((self.params.n_meta_nodes,), 0.9)
        # State: System Entropy Proxy
        self.entropy_proxy = 0.0
        # State: Veto Status
        self.veto_active = jnp.zeros((self.params.n_meta_nodes,))

    def encode(self, domain_state: Any) -> jnp.ndarray:
        """
        Maps director's will to stochastic bitstreams.
        """
        self.rng_key, subkey = split_rng(self.rng_key)
        rands = uniform(subkey, (self.params.n_meta_nodes, self.params.bitstream_length))
        # Will is reduced when Veto is active
        effective_will = self.meta_will * (1.0 - self.veto_active)
        bitstreams: jnp.ndarray = (rands < effective_will[:, None]).astype(jnp.uint8)
        return bitstreams

    @staticmethod
    @maybe_jit
    def _director_kernel(
        will: jnp.ndarray, gci_input: float, entropy: float, threshold: float, dt: float
    ) -> Tuple[jnp.ndarray, jnp.ndarray]:
        """
        Solves the Recursive Closure dynamics:
        dWill/dt = GCI - Entropy_Loss
        """
        # Ethical Veto: Active if entropy exceeds threshold
        veto = jnp.array(entropy > threshold).astype(jnp.float32)

        # Will grows with system coherence (GCI), decays with entropy
        d_will = 0.1 * gci_input - 0.2 * entropy
        will_next = jnp.clip(will + d_will * dt, 0.0, 1.0)

        return will_next, jnp.full_like(will, veto)

    def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
        """
        Advances the L16 holonomic dynamics using JAX.

        inputs: (1, bitstream_length) representing L15 GCI executive signal.
        Returns: (n_meta_nodes, bitstream_length) output bitstreams (The Master Directive).
        """
        # 1. Extract Global Coherence feedback (L15 -> L16)
        if inputs is not None:
            # First calculate mean as a JAX array, then convert to float
            gci_val = jnp.mean(inputs.astype(jnp.float32))
            gci_signal = float(gci_val)
        else:
            gci_val = jnp.array(0.5)
            gci_signal = 0.5

        # 2. Update Entropy Proxy (Inverse of coherence stability)
        self.entropy_proxy = 0.9 * self.entropy_proxy + 0.1 * (1.0 - gci_signal)

        # 3. Execute Director Kernel
        self.meta_will, self.veto_active = self._director_kernel(
            self.meta_will, float(gci_val), self.entropy_proxy, self.params.veto_threshold, dt
        )

        # 4. Return encoded bitstreams (The Master Directive)
        return self.encode(None)

    def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
        """
        Maps bitstreams back to Cybernetic Will index.
        """
        return {"meta_coherence_r16": float(jnp.mean(bitstreams.astype(jnp.float32)))}

    def get_metrics(self) -> Dict[str, float]:
        """
        Returns L16-specific metrics.
        """
        return {
            "director_will": float(jnp.mean(self.meta_will)),
            "system_entropy": float(self.entropy_proxy),
            "veto_active": float(jnp.mean(self.veto_active)),
        }

encode(domain_state)

Maps director's will to stochastic bitstreams.

Source code in src/sc_neurocore/adapters/holonomic/l16_meta.py
Python
61
62
63
64
65
66
67
68
69
70
def encode(self, domain_state: Any) -> jnp.ndarray:
    """
    Maps director's will to stochastic bitstreams.
    """
    self.rng_key, subkey = split_rng(self.rng_key)
    rands = uniform(subkey, (self.params.n_meta_nodes, self.params.bitstream_length))
    # Will is reduced when Veto is active
    effective_will = self.meta_will * (1.0 - self.veto_active)
    bitstreams: jnp.ndarray = (rands < effective_will[:, None]).astype(jnp.uint8)
    return bitstreams

step_jax(dt, inputs=None)

Advances the L16 holonomic dynamics using JAX.

inputs: (1, bitstream_length) representing L15 GCI executive signal. Returns: (n_meta_nodes, bitstream_length) output bitstreams (The Master Directive).

Source code in src/sc_neurocore/adapters/holonomic/l16_meta.py
Python
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def step_jax(self, dt: float, inputs: Optional[jnp.ndarray] = None) -> jnp.ndarray:
    """
    Advances the L16 holonomic dynamics using JAX.

    inputs: (1, bitstream_length) representing L15 GCI executive signal.
    Returns: (n_meta_nodes, bitstream_length) output bitstreams (The Master Directive).
    """
    # 1. Extract Global Coherence feedback (L15 -> L16)
    if inputs is not None:
        # First calculate mean as a JAX array, then convert to float
        gci_val = jnp.mean(inputs.astype(jnp.float32))
        gci_signal = float(gci_val)
    else:
        gci_val = jnp.array(0.5)
        gci_signal = 0.5

    # 2. Update Entropy Proxy (Inverse of coherence stability)
    self.entropy_proxy = 0.9 * self.entropy_proxy + 0.1 * (1.0 - gci_signal)

    # 3. Execute Director Kernel
    self.meta_will, self.veto_active = self._director_kernel(
        self.meta_will, float(gci_val), self.entropy_proxy, self.params.veto_threshold, dt
    )

    # 4. Return encoded bitstreams (The Master Directive)
    return self.encode(None)

decode(bitstreams)

Maps bitstreams back to Cybernetic Will index.

Source code in src/sc_neurocore/adapters/holonomic/l16_meta.py
Python
117
118
119
120
121
def decode(self, bitstreams: jnp.ndarray) -> Dict[str, float]:
    """
    Maps bitstreams back to Cybernetic Will index.
    """
    return {"meta_coherence_r16": float(jnp.mean(bitstreams.astype(jnp.float32)))}

get_metrics()

Returns L16-specific metrics.

Source code in src/sc_neurocore/adapters/holonomic/l16_meta.py
Python
123
124
125
126
127
128
129
130
131
def get_metrics(self) -> Dict[str, float]:
    """
    Returns L16-specific metrics.
    """
    return {
        "director_will": float(jnp.mean(self.meta_will)),
        "system_entropy": float(self.entropy_proxy),
        "veto_active": float(jnp.mean(self.veto_active)),
    }

create_adapter(layer)

Factory: create adapter by layer number (1-16).

Source code in src/sc_neurocore/adapters/holonomic/__init__.py
Python
62
63
64
65
66
def create_adapter(layer: int) -> Any:
    """Factory: create adapter by layer number (1-16)."""
    if layer not in _LAYER_MAP:
        raise ValueError(f"Layer {layer} not in 1-16")
    return _LAYER_MAP[layer]()

L6 Planetary Adapter Contract

sc_neurocore.adapters.holonomic.l6_plan.L6_PlanetaryAdapter accepts optional rank-2 upstream bitstream batches shaped (N, bitstream_length). The adapter validates positive integer region dimensions, positive finite Schumann frequency, cavity quality, Gaia coupling, bounded percolation threshold, positive finite dt, non-empty input rows, exact bitstream width, and finite input values before mutating planetary field state. If N differs from n_regions, the mean regional drive is broadcast deterministically across all configured regions.

The Python/JAX adapter owns the runtime Gaia-field update. The Rust safety mirror, Julia mirror, and Mojo validation shim expose the same parameter, timestep, and input-projection boundaries for downstream generated-kernel checks; they are not benchmark-dispatched acceleration paths.

L9 Memory Adapter Contract

sc_neurocore.adapters.holonomic.l9_mem.L9_MemoryAdapter accepts optional rank-2 upstream bitstream batches shaped (N, bitstream_length). The adapter now validates positive integer memory dimensions, finite non-negative retrieval gain, bounded weak-measurement strength, positive finite dt, non-empty input rows, exact bitstream width, and finite input values before mutating its forward/backward TSVF state. If N differs from n_memory_slots, rows are tiled deterministically by slot index instead of relying on backend modulo or broadcasting errors.

The Python/JAX adapter owns the runtime TSVF update. The Rust safety mirror, Julia mirror, and Mojo validation shim expose the same parameter, timestep, and input-projection boundaries for downstream generated-kernel checks; they are not benchmark-dispatched acceleration paths.

L13 Source-Field Adapter Contract

sc_neurocore.adapters.holonomic.l13_source.L13_SourceAdapter accepts optional L16 cybernetic-closure feedback as a scalar, rank-1 vector, or rank-2 batch. The adapter validates positive integer vacuum dimensions, finite primordial coupling and source bias, finite non-negative scission drive, positive finite dt, non-empty feedback vectors/batches, rank at most 2, and finite input values before mutating vacuum or Fisher-metric state. Scalars broadcast across all nodes; mismatched vector lengths or batch row counts broadcast the mean feedback drive deterministically across the configured vacuum lattice.

The Python/JAX adapter owns the runtime source-field update. The Rust safety mirror, Julia mirror, and Mojo validation shim expose the same parameter, timestep, feedback-projection, and decode boundaries for downstream generated-kernel checks; they are not benchmark-dispatched acceleration paths.

SpikeInterface / Neo Adapter

Import experimental spike data into SC-NeuroCore. Converts between SpikeInterface sorting results and SC-NeuroCore representations (bitstream matrices, Population inputs, SC probabilities).

sc_neurocore.adapters.spikeinterface

SpikeInterface/Neo adapter: import experimental spike data into SC-NeuroCore.

Converts between SpikeInterface sorting results (or raw spike trains) and SC-NeuroCore's internal representations (Population spike arrays, TensorStream, bitstream encoding).

Without SpikeInterface installed, provides pure-NumPy conversion functions that accept the same data format (unit_ids, spike_times).

Text Only
from sc_neurocore.adapters.spikeinterface import (
    spike_trains_to_bitstreams,
    spike_trains_to_population_input,
    from_sorting,  # requires spikeinterface
)

spike_trains_to_bitstreams(spike_times, duration_ms, dt=1.0)

Convert spike times to binary bitstream matrix.

Parameters

spike_times : dict mapping unit_id → array of spike times (ms) duration_ms : float Total recording duration in ms. dt : float Time bin width in ms.

Returns

np.ndarray Shape (n_units, n_bins), dtype uint8, binary {0, 1}.

Source code in src/sc_neurocore/adapters/spikeinterface.py
Python
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def spike_trains_to_bitstreams(
    spike_times: dict[int, np.ndarray[Any, Any]],
    duration_ms: float,
    dt: float = 1.0,
) -> np.ndarray[Any, Any]:
    """Convert spike times to binary bitstream matrix.

    Parameters
    ----------
    spike_times : dict mapping unit_id → array of spike times (ms)
    duration_ms : float
        Total recording duration in ms.
    dt : float
        Time bin width in ms.

    Returns
    -------
    np.ndarray
        Shape (n_units, n_bins), dtype uint8, binary {0, 1}.
    """
    n_bins = int(np.ceil(duration_ms / dt))
    unit_ids = sorted(spike_times.keys())
    n_units = len(unit_ids)

    matrix = np.zeros((n_units, n_bins), dtype=np.uint8)
    for i, uid in enumerate(unit_ids):
        times = np.asarray(spike_times[uid], dtype=np.float64)
        bins = np.clip((times / dt).astype(int), 0, n_bins - 1)
        matrix[i, bins] = 1

    return matrix

spike_trains_to_population_input(spike_times, duration_ms, dt=1.0)

Convert spike times to current input array for Population.step_all().

Each spike becomes a current pulse of amplitude 1.0 at the spike time bin.

Parameters

spike_times : dict mapping unit_id → array of spike times (ms) duration_ms : float dt : float

Returns

np.ndarray Shape (n_timesteps, n_units), suitable for time-stepped simulation.

Source code in src/sc_neurocore/adapters/spikeinterface.py
Python
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def spike_trains_to_population_input(
    spike_times: dict[int, np.ndarray[Any, Any]],
    duration_ms: float,
    dt: float = 1.0,
) -> np.ndarray[Any, Any]:
    """Convert spike times to current input array for Population.step_all().

    Each spike becomes a current pulse of amplitude 1.0 at the spike time bin.

    Parameters
    ----------
    spike_times : dict mapping unit_id → array of spike times (ms)
    duration_ms : float
    dt : float

    Returns
    -------
    np.ndarray
        Shape (n_timesteps, n_units), suitable for time-stepped simulation.
    """
    bitstreams = spike_trains_to_bitstreams(spike_times, duration_ms, dt)
    return bitstreams.T.astype(np.float64)

firing_rates_to_sc_probs(spike_times, duration_ms, max_rate_hz=100.0)

Convert firing rates to SC probabilities in [0, 1].

Parameters

spike_times : dict mapping unit_id → array of spike times (ms) duration_ms : float max_rate_hz : float Rate corresponding to probability 1.0.

Returns

np.ndarray Shape (n_units,), probabilities in [0, 1].

Source code in src/sc_neurocore/adapters/spikeinterface.py
Python
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def firing_rates_to_sc_probs(
    spike_times: dict[int, np.ndarray[Any, Any]],
    duration_ms: float,
    max_rate_hz: float = 100.0,
) -> np.ndarray[Any, Any]:
    """Convert firing rates to SC probabilities in [0, 1].

    Parameters
    ----------
    spike_times : dict mapping unit_id → array of spike times (ms)
    duration_ms : float
    max_rate_hz : float
        Rate corresponding to probability 1.0.

    Returns
    -------
    np.ndarray
        Shape (n_units,), probabilities in [0, 1].
    """
    unit_ids = sorted(spike_times.keys())
    probs = np.zeros(len(unit_ids))
    for i, uid in enumerate(unit_ids):
        n_spikes = len(spike_times[uid])
        rate_hz = n_spikes / (duration_ms / 1000.0)
        probs[i] = np.clip(rate_hz / max_rate_hz, 0.0, 1.0)
    return probs

from_sorting(sorting, dt=1.0)

Convert a SpikeInterface SortingExtractor to bitstream matrix.

Parameters

sorting : spikeinterface.core.BaseSorting SpikeInterface sorting result. dt : float Time bin width in ms.

Returns

np.ndarray Shape (n_units, n_bins), dtype uint8.

Source code in src/sc_neurocore/adapters/spikeinterface.py
Python
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def from_sorting(sorting: Any, dt: float = 1.0) -> np.ndarray[Any, Any]:  # pragma: no cover
    """Convert a SpikeInterface SortingExtractor to bitstream matrix.

    Parameters
    ----------
    sorting : spikeinterface.core.BaseSorting
        SpikeInterface sorting result.
    dt : float
        Time bin width in ms.

    Returns
    -------
    np.ndarray
        Shape (n_units, n_bins), dtype uint8.
    """
    unit_ids = sorting.get_unit_ids()
    fs = sorting.get_sampling_frequency()
    n_frames = sorting.get_total_samples()
    duration_ms = n_frames / fs * 1000.0

    spike_times = {}
    for uid in unit_ids:
        frames = sorting.get_unit_spike_train(uid)
        spike_times[int(uid)] = frames / fs * 1000.0  # convert to ms

    return spike_trains_to_bitstreams(spike_times, duration_ms, dt)

Plugin Discovery

Adapter discovery is backed by Python packaging entry points in group sc_neurocore.adapters. SC-NeuroCore declares first-party entry points for the class-oriented NeuroML, SONATA, SpikeInterface, DNA storage, genetic-regulatory, and neuromodulation adapter surfaces in pyproject.toml; editable source checkouts also register the same first-party classes through discover_adapters(include_entry_points=False) when the adapter registry is lazy-loaded. Third-party entry points are loaded only when callers explicitly run discover_adapters() with the default include_entry_points=True.

The global ComponentRegistry stores adapter classes. Historical importer functions remain available from their original modules, while registry discovery uses thin classes in sc_neurocore.adapters.importers.

sc_neurocore.utils.adapter_discovery

Discover and register adapter classes from Python entry-point metadata.

The adapter registry stores classes, not arbitrary callables. File-format import functions therefore enter the registry through thin adapter classes in sc_neurocore.adapters.importers while third-party packages may expose any class-compatible adapter target through the sc_neurocore.adapters entry point group.

ADAPTER_ENTRY_POINT_GROUP = 'sc_neurocore.adapters' module-attribute

Python packaging entry-point group used for adapter plugin discovery.

FIRST_PARTY_ADAPTERS = {'neuroml': 'sc_neurocore.adapters.importers:NeuroMLImporter', 'sonata': 'sc_neurocore.adapters.importers:SONATAImporter', 'spikeinterface': 'sc_neurocore.adapters.importers:SpikeInterfaceImporter', 'holonomic_dna_storage': 'sc_neurocore.adapters.holonomic.dna_storage:DNAEncoder', 'holonomic_grn': 'sc_neurocore.adapters.holonomic.grn:GeneticRegulatoryLayer', 'holonomic_neuromodulation': 'sc_neurocore.adapters.holonomic.neuromodulation:NeuromodulatorSystem'} module-attribute

Built-in adapter entry-point targets mirrored in pyproject.toml.

discover_adapters(*, include_first_party=True, include_entry_points=True)

Discover adapter classes and register them in the global registry.

Parameters

include_first_party : bool, default=True Register the built-in adapter importers declared by :data:FIRST_PARTY_ADAPTERS. This source-level path keeps editable checkouts wired even before packaging metadata is installed. include_entry_points : bool, default=True Load installed third-party plugins from :data:ADAPTER_ENTRY_POINT_GROUP through importlib.metadata.

Returns

dict[str, type] Mapping from registry name to the discovered adapter class. Duplicate registry entries are tolerated so repeated discovery is idempotent.

Source code in src/sc_neurocore/utils/adapter_discovery.py
Python
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def discover_adapters(
    *,
    include_first_party: bool = True,
    include_entry_points: bool = True,
) -> dict[str, type]:
    """Discover adapter classes and register them in the global registry.

    Parameters
    ----------
    include_first_party : bool, default=True
        Register the built-in adapter importers declared by
        :data:`FIRST_PARTY_ADAPTERS`.  This source-level path keeps editable
        checkouts wired even before packaging metadata is installed.
    include_entry_points : bool, default=True
        Load installed third-party plugins from
        :data:`ADAPTER_ENTRY_POINT_GROUP` through ``importlib.metadata``.

    Returns
    -------
    dict[str, type]
        Mapping from registry name to the discovered adapter class. Duplicate
        registry entries are tolerated so repeated discovery is idempotent.
    """
    found: dict[str, type] = {}

    if include_first_party:
        for name, target in FIRST_PARTY_ADAPTERS.items():
            try:
                adapter_type = _resolve_target(target)
            except _DISCOVERY_ERRORS:
                continue
            _register_adapter(name, adapter_type)
            found[name] = adapter_type
        _ensure_holonomic_adapters_loaded()

    if not include_entry_points:
        return found

    for ep in _entry_points(ADAPTER_ENTRY_POINT_GROUP):
        try:
            loaded = ep.load()
            if not isinstance(loaded, type):
                raise TypeError(f"Adapter entry point is not a class: {ep.name!r}")
            name = ep.name
            _register_adapter(name, loaded)
            found[name] = loaded
        except _DISCOVERY_ERRORS:
            continue

    return found

sc_neurocore.adapters.importers

Registry adapter classes for SC-NeuroCore importer modules.

The historical importer APIs are plain functions. These small classes make the same functionality discoverable through the class-oriented ComponentRegistry and Python packaging entry points without changing the function-level APIs used by existing callers.

NeuroMLImporter

Class-oriented registry surface for NeuroML 2 cell imports.

Source code in src/sc_neurocore/adapters/importers.py
Python
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class NeuroMLImporter:
    """Class-oriented registry surface for NeuroML 2 cell imports."""

    @staticmethod
    def import_cells(path: str | Path) -> list[ImportedCell]:
        """Parse a NeuroML 2 XML file into imported cell definitions.

        Parameters
        ----------
        path : str or Path
            Local ``.nml`` or ``.xml`` file containing NeuroML 2 cell elements.

        Returns
        -------
        list of ImportedCell
            Parsed cell definitions ready for SC-NeuroCore neuron creation.
        """
        from sc_neurocore.adapters.neuroml import import_neuroml

        return import_neuroml(path)

    @staticmethod
    def create_neuron(cell: ImportedCell) -> Any:
        """Instantiate a neuron from a parsed NeuroML cell definition.

        Parameters
        ----------
        cell : ImportedCell
            Parsed NeuroML cell definition returned by :meth:`import_cells`.

        Returns
        -------
        Any
            Concrete SC-NeuroCore neuron instance selected by the cell type.
        """
        from sc_neurocore.adapters.neuroml import create_neuron

        return create_neuron(cell)

import_cells(path) staticmethod

Parse a NeuroML 2 XML file into imported cell definitions.

Parameters

path : str or Path Local .nml or .xml file containing NeuroML 2 cell elements.

Returns

list of ImportedCell Parsed cell definitions ready for SC-NeuroCore neuron creation.

Source code in src/sc_neurocore/adapters/importers.py
Python
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@staticmethod
def import_cells(path: str | Path) -> list[ImportedCell]:
    """Parse a NeuroML 2 XML file into imported cell definitions.

    Parameters
    ----------
    path : str or Path
        Local ``.nml`` or ``.xml`` file containing NeuroML 2 cell elements.

    Returns
    -------
    list of ImportedCell
        Parsed cell definitions ready for SC-NeuroCore neuron creation.
    """
    from sc_neurocore.adapters.neuroml import import_neuroml

    return import_neuroml(path)

create_neuron(cell) staticmethod

Instantiate a neuron from a parsed NeuroML cell definition.

Parameters

cell : ImportedCell Parsed NeuroML cell definition returned by :meth:import_cells.

Returns

Any Concrete SC-NeuroCore neuron instance selected by the cell type.

Source code in src/sc_neurocore/adapters/importers.py
Python
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@staticmethod
def create_neuron(cell: ImportedCell) -> Any:
    """Instantiate a neuron from a parsed NeuroML cell definition.

    Parameters
    ----------
    cell : ImportedCell
        Parsed NeuroML cell definition returned by :meth:`import_cells`.

    Returns
    -------
    Any
        Concrete SC-NeuroCore neuron instance selected by the cell type.
    """
    from sc_neurocore.adapters.neuroml import create_neuron

    return create_neuron(cell)

SONATAImporter

Class-oriented registry surface for SONATA network imports.

Source code in src/sc_neurocore/adapters/importers.py
Python
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class SONATAImporter:
    """Class-oriented registry surface for SONATA network imports."""

    @staticmethod
    def import_network(
        nodes_path: str | Path,
        edges_path: str | Path | None = None,
    ) -> SONATANetwork:
        """Import a SONATA network from nodes and optional edges files.

        Parameters
        ----------
        nodes_path : str or Path
            Path to a SONATA ``nodes.h5`` file.
        edges_path : str or Path, optional
            Optional path to a SONATA ``edges.h5`` file.

        Returns
        -------
        SONATANetwork
            Parsed nodes, edges, population metadata, and connectivity helpers.
        """
        from sc_neurocore.adapters.sonata import import_sonata

        return import_sonata(nodes_path, edges_path)

import_network(nodes_path, edges_path=None) staticmethod

Import a SONATA network from nodes and optional edges files.

Parameters

nodes_path : str or Path Path to a SONATA nodes.h5 file. edges_path : str or Path, optional Optional path to a SONATA edges.h5 file.

Returns

SONATANetwork Parsed nodes, edges, population metadata, and connectivity helpers.

Source code in src/sc_neurocore/adapters/importers.py
Python
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
@staticmethod
def import_network(
    nodes_path: str | Path,
    edges_path: str | Path | None = None,
) -> SONATANetwork:
    """Import a SONATA network from nodes and optional edges files.

    Parameters
    ----------
    nodes_path : str or Path
        Path to a SONATA ``nodes.h5`` file.
    edges_path : str or Path, optional
        Optional path to a SONATA ``edges.h5`` file.

    Returns
    -------
    SONATANetwork
        Parsed nodes, edges, population metadata, and connectivity helpers.
    """
    from sc_neurocore.adapters.sonata import import_sonata

    return import_sonata(nodes_path, edges_path)

SpikeInterfaceImporter

Class-oriented registry surface for spike-train conversion imports.

Source code in src/sc_neurocore/adapters/importers.py
Python
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
class SpikeInterfaceImporter:
    """Class-oriented registry surface for spike-train conversion imports."""

    @staticmethod
    def to_bitstreams(
        spike_times: dict[int, np.ndarray[Any, Any]],
        duration_ms: float,
        dt: float = 1.0,
    ) -> np.ndarray[Any, Any]:
        """Convert spike times to a binary bitstream matrix.

        Parameters
        ----------
        spike_times : dict[int, np.ndarray]
            Mapping from unit identifier to spike times in milliseconds.
        duration_ms : float
            Recording duration in milliseconds.
        dt : float, default=1.0
            Time-bin width in milliseconds.

        Returns
        -------
        np.ndarray
            Binary matrix shaped ``(n_units, n_bins)`` with dtype ``uint8``.
        """
        from sc_neurocore.adapters.spikeinterface import spike_trains_to_bitstreams

        return spike_trains_to_bitstreams(spike_times, duration_ms, dt)

    @staticmethod
    def to_population_input(
        spike_times: dict[int, np.ndarray[Any, Any]],
        duration_ms: float,
        dt: float = 1.0,
    ) -> np.ndarray[Any, Any]:
        """Convert spike times to ``Population.step_all`` input.

        Parameters
        ----------
        spike_times : dict[int, np.ndarray]
            Mapping from unit identifier to spike times in milliseconds.
        duration_ms : float
            Recording duration in milliseconds.
        dt : float, default=1.0
            Time-bin width in milliseconds.

        Returns
        -------
        np.ndarray
            Floating-point array shaped ``(n_timesteps, n_units)``.
        """
        from sc_neurocore.adapters.spikeinterface import spike_trains_to_population_input

        return spike_trains_to_population_input(spike_times, duration_ms, dt)

    @staticmethod
    def to_probabilities(
        spike_times: dict[int, np.ndarray[Any, Any]],
        duration_ms: float,
        max_rate_hz: float = 100.0,
    ) -> np.ndarray[Any, Any]:
        """Convert spike trains into bounded stochastic-computing probabilities.

        Parameters
        ----------
        spike_times : dict[int, np.ndarray]
            Mapping from unit identifier to spike times in milliseconds.
        duration_ms : float
            Recording duration in milliseconds.
        max_rate_hz : float, default=100.0
            Firing rate that maps to probability ``1.0``.

        Returns
        -------
        np.ndarray
            Probability vector shaped ``(n_units,)`` and bounded in ``[0, 1]``.
        """
        from sc_neurocore.adapters.spikeinterface import firing_rates_to_sc_probs

        return firing_rates_to_sc_probs(spike_times, duration_ms, max_rate_hz)

to_bitstreams(spike_times, duration_ms, dt=1.0) staticmethod

Convert spike times to a binary bitstream matrix.

Parameters

spike_times : dict[int, np.ndarray] Mapping from unit identifier to spike times in milliseconds. duration_ms : float Recording duration in milliseconds. dt : float, default=1.0 Time-bin width in milliseconds.

Returns

np.ndarray Binary matrix shaped (n_units, n_bins) with dtype uint8.

Source code in src/sc_neurocore/adapters/importers.py
Python
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
@staticmethod
def to_bitstreams(
    spike_times: dict[int, np.ndarray[Any, Any]],
    duration_ms: float,
    dt: float = 1.0,
) -> np.ndarray[Any, Any]:
    """Convert spike times to a binary bitstream matrix.

    Parameters
    ----------
    spike_times : dict[int, np.ndarray]
        Mapping from unit identifier to spike times in milliseconds.
    duration_ms : float
        Recording duration in milliseconds.
    dt : float, default=1.0
        Time-bin width in milliseconds.

    Returns
    -------
    np.ndarray
        Binary matrix shaped ``(n_units, n_bins)`` with dtype ``uint8``.
    """
    from sc_neurocore.adapters.spikeinterface import spike_trains_to_bitstreams

    return spike_trains_to_bitstreams(spike_times, duration_ms, dt)

to_population_input(spike_times, duration_ms, dt=1.0) staticmethod

Convert spike times to Population.step_all input.

Parameters

spike_times : dict[int, np.ndarray] Mapping from unit identifier to spike times in milliseconds. duration_ms : float Recording duration in milliseconds. dt : float, default=1.0 Time-bin width in milliseconds.

Returns

np.ndarray Floating-point array shaped (n_timesteps, n_units).

Source code in src/sc_neurocore/adapters/importers.py
Python
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
@staticmethod
def to_population_input(
    spike_times: dict[int, np.ndarray[Any, Any]],
    duration_ms: float,
    dt: float = 1.0,
) -> np.ndarray[Any, Any]:
    """Convert spike times to ``Population.step_all`` input.

    Parameters
    ----------
    spike_times : dict[int, np.ndarray]
        Mapping from unit identifier to spike times in milliseconds.
    duration_ms : float
        Recording duration in milliseconds.
    dt : float, default=1.0
        Time-bin width in milliseconds.

    Returns
    -------
    np.ndarray
        Floating-point array shaped ``(n_timesteps, n_units)``.
    """
    from sc_neurocore.adapters.spikeinterface import spike_trains_to_population_input

    return spike_trains_to_population_input(spike_times, duration_ms, dt)

to_probabilities(spike_times, duration_ms, max_rate_hz=100.0) staticmethod

Convert spike trains into bounded stochastic-computing probabilities.

Parameters

spike_times : dict[int, np.ndarray] Mapping from unit identifier to spike times in milliseconds. duration_ms : float Recording duration in milliseconds. max_rate_hz : float, default=100.0 Firing rate that maps to probability 1.0.

Returns

np.ndarray Probability vector shaped (n_units,) and bounded in [0, 1].

Source code in src/sc_neurocore/adapters/importers.py
Python
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
@staticmethod
def to_probabilities(
    spike_times: dict[int, np.ndarray[Any, Any]],
    duration_ms: float,
    max_rate_hz: float = 100.0,
) -> np.ndarray[Any, Any]:
    """Convert spike trains into bounded stochastic-computing probabilities.

    Parameters
    ----------
    spike_times : dict[int, np.ndarray]
        Mapping from unit identifier to spike times in milliseconds.
    duration_ms : float
        Recording duration in milliseconds.
    max_rate_hz : float, default=100.0
        Firing rate that maps to probability ``1.0``.

    Returns
    -------
    np.ndarray
        Probability vector shaped ``(n_units,)`` and bounded in ``[0, 1]``.
    """
    from sc_neurocore.adapters.spikeinterface import firing_rates_to_sc_probs

    return firing_rates_to_sc_probs(spike_times, duration_ms, max_rate_hz)