Bioware Interface¶
Biological-hardware interface for cerebral organoids and multi-electrode array (MEA) systems. Bridges wet-lab experiments with in-silico SC simulations — spike detection, AER transcoding, stochastic-computing feedback, optogenetic encoding, Q8.8 homeostatic plasticity, PCA spike sorting, and a closed-loop session layer that orchestrates the full pipeline per frame.
from sc_neurocore.bioware.bioware import (
BioHybridSession, BioHybridFrameResult,
MEAConfig, MEALayout, SpikeDetector,
MEAToAERTranscoder, AERToSCConverter, SCToOptoEncoder,
CultureHealth, HomeostaticPlasticity, SpikeSorter,
mea_fitness_hook,
)
1. Mathematical formalism¶
1.1 Spike detection (adaptive threshold, MAD-based noise)¶
Raw MEA voltage $V_c(t)$ per channel $c$ is detected against an adaptive threshold derived from the median absolute deviation:
$$ \sigma_c = \frac{\mathrm{median}_t |V_c(t)|}{0.6745}, \qquad \theta_c = \alpha\,\sigma_c. $$
The constant $0.6745$ converts MAD into an estimator of the Gaussian
standard deviation (Donoho & Johnstone 1994); $\alpha = 5$ by default
(spike_threshold_sigma). A spike is emitted when
$|V_c(t)| > \theta_c$ and no spike was emitted on the same channel in
the preceding refractory_samples = 30 samples.
1.2 MEA → AER transcoding¶
For a spike with real-time timestamp $t_s$ (seconds) and a hardware AER clock $f_\text{hw}$ (Hz), the AER event carries integer tick
$$ \tau = \lfloor t_s \cdot f_\text{hw} \rfloor $$
and neuron id derived from channel_map (or the channel number
itself if no map is given). AER events are emitted sorted by $\tau$.
1.3 AER → SC bitstream conversion¶
For each neuron id, the converter bins AER timestamps into a bitstream of length $L$ (default 1 024). For neuron $n$ observed over the window $[t_0, t_0 + T]$ with $k_n$ spikes:
$$ p_n = \frac{k_n}{k_n + K}, \qquad b_{n,i} \sim \mathrm{Bernoulli}(p_n), \qquad i \in [0, L). $$
where $K$ is a smoothing constant (smoothing_constant, default 1).
The resulting SC bitstream has mean activity equal to $p_n$.
1.4 Optogenetic encoding (SC → opto pulses)¶
Given an output bitstream $b \in {0, 1}^L$ with density $d = \frac{1}{L}\sum_i b_i$, the optogenetic pulse uses intensity
$$ I_\text{mW/mm²} = d \cdot I_\text{max}, $$
and duration
$$ T_\text{ms} = T_\text{min} + (T_\text{max} - T_\text{min})\,d, $$
so bright / long pulses signal high-activity layers and dark / short
pulses signal low-activity. The wavelength is fixed by the
optogenetic channel (wavelength_nm, e.g. 470 nm for ChR2).
1.5 Biological STDP (Bi & Poo 1998, exponential pair rule)¶
For a post-spike timed at $t_\text{post}$ after a pre-spike at $t_\text{pre}$, let $\Delta t = t_\text{post} - t_\text{pre}$. The weight change is:
$$ \Delta w(\Delta t) = \begin{cases} A_+\, \exp(-\Delta t / \tau_+) & \Delta t > 0 \text{ (LTP)} \ -A_-\, \exp(+\Delta t / \tau_-) & \Delta t < 0 \text{ (LTD)} \ 0 & \Delta t = 0 \end{cases} $$
Default $\tau_+ = \tau_- = 20$ ms, $A_+ = 0.005$, $A_- = 0.00525$, matching Bi & Poo 1998 hippocampal culture fits (1:1.05 potentiation:depression asymmetry).
1.6 BCM metaplasticity (sliding-threshold variant)¶
The BCM rule (Bienenstock, Cooper, Munro 1982) adjusts the LTP/LTD boundary as a function of post-synaptic activity $\bar y$:
$$ \Delta w = \eta\,x\,y\,(y - \theta_m), \qquad \theta_m = \kappa\, \bar y^2, $$
where $\bar y$ is the temporally-averaged post-synaptic rate and $\kappa > 0$ tunes the sliding-threshold curvature. Low-frequency activity below $\theta_m$ depresses; above, potentiates.
1.7 Q8.8 homeostatic controller¶
HomeostaticPlasticity.update_threshold implements a proportional
negative-feedback controller in fixed-point Q8.8 arithmetic:
$$ \alpha_t = \frac{\Delta t_\text{ms}}{\tau_\text{homeo}}, \qquad \Delta \theta = \lfloor \alpha_t (r_t - r^\star) \cdot 256 \rfloor, $$
$$ \theta^{(q88)}{t+1} = \mathrm{clip}!\left(\theta^{(q88)}_t + \Delta \theta, \theta^{(q88)}\text{min}, \theta^{(q88)}_\text{max}\right). $$
The factor $256$ is the Q8.8 scale: one full threshold unit in floating-point corresponds to $256$ steps in the integer representation. A 1 Hz rate error sustained over one full time constant $\tau_\text{homeo}$ thus shifts the threshold by exactly one unit.
1.8 PCA + KMeans spike sorting¶
Given a set of detected waveforms ${w^{(i)}}$, each a vector in
$\mathbb{R}^D$ (with $D$ = int(2 · snippet_ms · sample_rate_hz /
1000)), sorting proceeds in two stages:
- Dimensionality reduction via principal component analysis:
$$ X = [w^{(1)}, \ldots, w^{(M)}]^\top \in \mathbb{R}^{M\times D}, \qquad X = U \Sigma V^\top, \qquad Z = X \cdot V_{:k}, $$
with $k = \min(\text{n_components}, M, D)$ (default
n_components = 3).
- Cluster assignment via $k$-means with $k = \text{num_units}$ and $n_\text{init} = 10$ restarts:
$$ \min_{{\mu_c}} \sum_{i=1}^M \min_{c \in {1..k}} |z^{(i)} - \mu_c|^2. $$
Waveforms flagged waveform is None (amplitude-only spikes) are
skipped; the sorter is a no-op when fewer than num_units waveforms
are available.
1.9 Evo-substrate fitness hook¶
The MEA → ReplicationEngine bridge computes three fitness scalars:
$$ \bar r = \frac{1}{|C|}\sum_{c \in C} \frac{k_c}{T_\mathrm{frame}}, \qquad \mathrm{acc} = \mathrm{clip}!\left(1 - \frac{|\bar r - r^\star|}{r^\star},\; 0.1,\; 0.99\right), $$
where $k_c$ is the per-channel spike count, $T_\mathrm{frame}$ is
duration_s when supplied, and $r^\star$ is the target rate
(target_rate = 10 Hz by default). When duration_s is omitted,
the hook preserves the legacy count-domain score for callers that do
not know the frame length. Energy and latency:
$$ E = 0.5\,\text{mW} \cdot N_\text{spikes}, \qquad T_\mathrm{lat} = \begin{cases} T_\mathrm{measured}, & \text{if measured latency is supplied},\ t_\mathrm{first\ response} - t_\mathrm{stim}, & \text{if stimulus time is supplied},\ t_\mathrm{first\ spike}, & \text{otherwise}. \end{cases} $$
2. Theoretical context¶
Bioware sits at the intersection of three active research frontiers.
Closed-loop biohybrid experiments. Organoid cultures coupled to
MEAs via optogenetic actuators form a real-time feedback loop between
a digital controller and a living network. Kagan et al. (2022)
demonstrated such a system learning Pong; DishBrain and similar
platforms have generalised the paradigm to control tasks.
SC-NeuroCore's BioHybridSession is the orchestration layer — it
owns the MEA config, detector, transcoder, SC converter, opto
encoder, and plasticity updates, and guarantees the end-to-end
latency budget in a single process_frame call.
Stochastic computing over biological signals. Traditional MEA pipelines output rates or spike trains; SC-NeuroCore converts rates directly into Bernoulli bitstreams consumed by the SC arithmetic stack. The conversion is lossless up to the SC bit budget — $L = 1024$ bits encodes $p_n$ with variance $p(1-p)/L \le 1/(4L) \approx 2.4 \times 10^{-4}$.
Hardware-grounded homeostatic plasticity. The Q8.8 controller in
§1.7 is directly synthesisable — the state variable is an integer,
the update is additive with a constant shift, the clamp is a pair of
comparators. The same mathematical form runs on the PYNQ-Z2 silicon
(sc_aer_encoder.v and friends) as in Python, so simulations
quantitatively match hardware traces to Q8.8 precision. Turrigiano
2012 provides the biological reference point: real neurons use much
slower homeostatic timescales (seconds to hours), modelled here by
the tau_homeo_ms parameter.
Spike sorting. PCA + KMeans is the classical first-pass (Lewicki 1998); modern production systems use SpikeInterface, Kilosort or MountainSort. The SC-NeuroCore sorter is intentionally minimal — it exists so a single closed-loop run can demonstrate end-to-end separation of 2–4 units without external dependencies beyond scikit-learn, and so the evolutionary-substrate fitness hook has something to condition on when the MEA returns waveforms.
The overall bioware contract is stricter than typical research code:
every public surface is typed, exception-free for empty inputs,
deterministic under a fixed seed, and round-trippable between
dataclass and dict views. The contract is enforced by 40+ tests in
tests/test_bioware/test_bioware.py.
3. Pipeline position¶
Bioware is the outer of SC-NeuroCore's two closed loops. The inner loop is the SC arithmetic stack; the outer loop wraps it in a real-time bidirectional bridge with the biological substrate.
┌──────────── BioHybridSession.process_frame() ─────────────┐
│ │
│ voltage_data (N_samples × N_channels) │
│ │ │
│ ▼ │
│ SpikeDetector ──────► list[DetectedSpike] │
│ │ │ │
│ │ ├──► (opt) SpikeSorter │
│ │ ├──► (opt) ArtifactReject │
│ │ ▼ │
│ │ MEAToAERTranscoder │
│ │ │ list[AEREvent] │
│ │ ▼ │
│ │ AERToSCConverter │
│ │ │ dict[id, np.ndarray] │
│ │ ▼ │
│ │ SCToOptoEncoder ──► OptoPulse │
│ │ │
│ └──► CultureHealth ──► health score │
│ └──► HomeostaticPlasticity (Q8.8 threshold update) │
│ └──► ArcaneZenithCognitiveCore.step_from_bio_rates │
│ │
└────────► BioHybridFrameResult ──────────────────────────► │
caller
Upstream inputs — the MEA voltage matrix (from any MEA recording
system — PYNQ-Z2 ADC, Intan, BlackRock, synthetic). Format is
np.ndarray shape (n_samples, n_channels).
Downstream outputs — a :class:BioHybridFrameResult packet
containing spike counts, AER events, SC bitstreams, optogenetic
pulses, and a CultureHealth snapshot. Both dataclass-style
(result.round) and mapping-style (result["round"]) access
supported.
The outer loop is driven by the caller — no threads, no background
tasks inside process_frame. Hardware latency / jitter is a
caller concern.
4. Features¶
| Feature | Detail |
|---|---|
| MEA config presets | 60, 120, 256, 4 096 channel layouts with canonical electrode pitches |
| MAD-based spike detection | Robust σ estimator; per-channel adaptive threshold |
| Configurable refractory | Default 30 samples; prevents double-counting |
| Waveform snippet extraction | Per-spike 2 ms window, edge-padded |
| AER transcoding | Integer hardware timestamps; channel→neuron map; sorted output |
| AER → SC bitstream | Bernoulli density encoding with smoothing constant |
| SC → optogenetic encoding | Bright+long for high density; bounded wavelength / intensity / duration |
| Biological STDP | Exponential pair rule, Bi & Poo parameters |
| BCM metaplasticity | Sliding-threshold variant |
| Q8.8 homeostatic plasticity | Proportional controller with 1 Hz · τ_homeo = 1 unit calibration |
| Culture health | Rate-based aggregate score over the frame |
| PCA + KMeans spike sorting | Optional; scikit-learn optional dep |
| Artifact rejection | Optional stim-window blanking |
| Pharmacology model | Optional onset-delay + gain model for neurotransmitter pulses |
| Latency budget | Per-frame wall-clock recording |
| ArcaneZenith bridge | zenith_core.step_from_bio_rates(...) inside process_frame |
| Evo-substrate fitness hook | mea_fitness_hook(spikes, target_rate) → {acc, energy, latency} |
| BioHybridFrameResult dual interface | Dataclass attribute access + mapping result["key"] + in |
| Audit log | :class:BioAuditLog timestamp + entry record for every session |
| Multi-well plate support | :class:MultiWellPlate for parallel experiments |
| 40+ tests | Spike detection + AER + SC + Opto + STDP + BCM + Culture + Homeostasis |
5. Usage example with output¶
import numpy as np
from sc_neurocore.bioware.bioware import (
BioHybridSession, MEAConfig,
SpikeDetector, MEAToAERTranscoder, AERToSCConverter,
SCToOptoEncoder, BiologicalSTDP, CultureHealth,
HomeostaticPlasticity, SpikeSorter,
)
cfg = MEAConfig(num_channels=10, sample_rate_hz=20_000.0,
spike_threshold_sigma=5.0)
session = BioHybridSession(
mea_config=cfg,
detector=SpikeDetector(config=cfg, refractory_samples=30),
transcoder=MEAToAERTranscoder(hw_clock_hz=1e6),
sc_converter=AERToSCConverter(bitstream_length=1024),
opto_encoder=SCToOptoEncoder(wavelength_nm=470,
max_intensity_mw_mm2=5.0),
stdp=BiologicalSTDP(),
health_monitor=CultureHealth(),
homeostatic=HomeostaticPlasticity(target_rate_hz=10.0),
sorter=SpikeSorter(num_units=3),
)
rng = np.random.default_rng(42)
V = rng.normal(0, 5, size=(2000, 10))
V[::200, 0] = -80.0 # spikes on channel 0
V[100::200, 3] = -60.0 # spikes on channel 3
result = session.process_frame(V)
print(f"round : {result.round}")
print(f"num_spikes : {result.num_spikes}")
print(f"num_aer : {result.num_aer_events}")
print(f"num_streams : {result.num_bitstreams}")
print(f"num_opto : {result.num_opto_pulses}")
print(f"latency_us : {result.latency_us:.1f}")
# Dataclass AND mapping access both work:
assert result["round"] == result.round
assert "latency_us" in result
Typical output:
round : 1
num_spikes : 16
num_aer : 16
num_streams : 2
num_opto : 2
latency_us : 3178.4
The examples/14_bioware_closed_loop_demo.py script extends this to a
100-frame experiment with full SpikeSorter fit + ArcaneZenith cognitive
core + MEA hardware simulation; measured end-to-end wall-clock in §7.
6. Technical reference¶
6.1 MEAConfig + MEALayout¶
class MEALayout(Enum):
MEA_60 = "60ch"
MEA_120 = "120ch"
MEA_256 = "256ch"
MEA_4096 = "4096ch"
CUSTOM = "custom"
@dataclass
class MEAConfig:
layout: MEALayout = MEALayout.MEA_60
num_channels: int = 60
sample_rate_hz: float = 20_000.0
voltage_gain: float = 1000.0
noise_floor_uv: float = 5.0
spike_threshold_sigma: float = 5.0
electrode_pitch_um: float = 200.0
@classmethod
def from_layout(cls, layout: MEALayout) -> MEAConfig: ...
6.2 SpikeDetector + DetectedSpike¶
@dataclass
class DetectedSpike:
channel: int
timestamp_s: float
amplitude_uv: float
unit_id: int = 0
waveform: Optional[np.ndarray] = None
@dataclass
class SpikeDetector:
config: MEAConfig
refractory_samples: int = 30
def estimate_noise(self, voltage_data) -> np.ndarray
def detect(self, voltage_data, snippet_ms: float = 2.0) -> list[DetectedSpike]
6.3 MEAToAERTranscoder + AERToSCConverter¶
@dataclass
class AEREvent:
neuron_id: int
timestamp: int # clock ticks
valid: bool = True
weight: int = 256 # Q8.8 = 1.0
class MEAToAERTranscoder:
hw_clock_hz: float = 1e6
channel_map: Optional[dict[int, int]] = None
def transcode(self, spikes, t_start_s: float = 0.0) -> list[AEREvent]
class AERToSCConverter:
bitstream_length: int = 1024
smoothing_constant: float = 1.0
def convert(self, events) -> dict[int, np.ndarray]
6.4 SCToOptoEncoder + OptogeneticPulse¶
@dataclass
class OptogeneticPulse:
wavelength_nm: int
intensity_mw_mm2: float
duration_ms: float
channel_id: int
@dataclass
class SCToOptoEncoder:
wavelength_nm: int = 470
max_intensity_mw_mm2: float = 5.0
min_pulse_ms: float = 1.0
max_pulse_ms: float = 50.0
def encode(self, bitstreams) -> list[OptogeneticPulse]
6.5 Plasticity classes¶
@dataclass
class BiologicalSTDP:
A_plus: float = 0.005
A_minus: float = 0.00525
tau_plus_ms: float = 20.0
tau_minus_ms: float = 20.0
def compute_dw(self, dt_ms: float) -> float
@dataclass
class HomeostaticPlasticity:
target_rate_hz: float = 10.0
tau_homeo_ms: float = 10000.0
max_threshold_q88: int = 512 # Q8.8 = 2.0
min_threshold_q88: int = 64 # Q8.8 = 0.25
def update_threshold(self, current_q88: int,
observed_rate_hz: float,
dt_ms: float) -> int
@dataclass
class PharmModel:
agent_name: str = "none"
gain: float = 1.0
onset_delay_s: float = 30.0
wash_time_s: float = 120.0
def apply(self, t_current_s: float) -> None
def effective_gain(self, t_current_s: float) -> float
def modulate_spikes(self, spike_counts: np.ndarray,
t_current_s: float) -> np.ndarray
def modulate_spike_events(self, spikes: list[DetectedSpike],
t_current_s: float) -> list[DetectedSpike]
modulate_spike_events is the path used by
BioHybridSession.process_frame. Inhibitory gains deterministically
thin events across the observed response span, so the pharmacological
model does not bias output toward the earliest detected spikes.
Excitatory gains preserve the observed events and add
template-derived events inside the observed temporal support.
6.6 SpikeSorter¶
@dataclass
class SpikeSorter:
num_units: int = 4
n_components: int = 3
def fit(self, spikes: list[DetectedSpike]) -> None
def assign(self, spikes: list[DetectedSpike]) -> list[DetectedSpike]
fit imports scikit-learn only when enough waveforms are
present to cluster; amplitude-only spike lists no-op gracefully.
6.7 BioHybridSession + BioHybridFrameResult¶
@dataclass
class BioHybridFrameResult:
round: int
num_spikes: int
num_aer_events: int
num_bitstreams: int
num_opto_pulses: int
latency_us: float
health: Dict[str, Any]
spikes: List[DetectedSpike]
aer_events: List[AEREvent]
bitstreams: Dict[int, np.ndarray]
opto_pulses: List[OptogeneticPulse]
def __getitem__(self, key: str) -> Any
def __contains__(self, key: object) -> bool
def keys(self) -> List[str]
@dataclass
class BioHybridSession:
mea_config: MEAConfig
detector: SpikeDetector
transcoder: MEAToAERTranscoder
sc_converter: AERToSCConverter
opto_encoder: SCToOptoEncoder
stdp: BiologicalSTDP = ...
health_monitor: CultureHealth = ...
artifact_rejector: Optional[ArtifactRejector] = None
pharm_model: Optional[PharmModel] = None
latency_budget: Optional[LatencyBudget] = None
homeostatic: Optional[HomeostaticPlasticity] = None
sorter: Optional[SpikeSorter] = None
zenith_core: Optional[ArcaneZenithCognitiveCore] = None
round_count: int = 0
def process_frame(
self,
voltage_data: np.ndarray,
t_start_s: float = 0.0,
stim_times_s: Optional[list[float]] = None,
) -> BioHybridFrameResult
6.8 mea_fitness_hook¶
def mea_fitness_hook(
detected_spikes: list[DetectedSpike],
target_rate: float = 10.0,
*,
duration_s: float | None = None,
stimulus_time_s: float | None = None,
measured_latency_ms: float | None = None,
) -> dict[str, float]
Returns {"accuracy", "energy_mw", "latency_ms"}. Empty input
returns the floor {0.1, 0.0, 0.0}; target_rate == 0 also
returns the floor accuracy. duration_s must be finite and
positive when supplied. stimulus_time_s and
measured_latency_ms must be finite; measured latency must be
non-negative. Groups spikes by DetectedSpike.channel (regression
guard against the previous channel_id bug).
7. Performance benchmarks¶
All numbers measured 2026-04-20 on Linux x86-64 (Intel i5-11600K,
CPython 3.12.3, scikit-learn 1.8, NumPy 2.2). Committed bench harness:
benchmarks/bench_bioware.py — JSON at
benchmarks/results/bench_bioware.json. Reproducer scripts also in §7.4.
Note: the demo uses uniform-random MEA voltage and ArcaneZenith receives
a stochastic current stream; identity_drift and per-frame latency
therefore vary ≈10 % between runs. The figures in the next two tables
come from one concrete run; the demo wall-time (≈0.69 s on the
reference host) is stable.
7.1 End-to-end closed-loop latency¶
| Scenario | Wall time | Per-frame latency |
|---|---|---|
| 14_bioware_closed_loop_demo (100 frames) | 0.69 s | 2 945 µs at frame 100 |
Full pipeline: synthetic MEA → SpikeDetector →
SpikeSorter (PCA-fitted on 177 training waveforms) →
MEAToAERTranscoder → AERToSCConverter → SCToOptoEncoder →
:class:CultureHealth + :class:HomeostaticPlasticity update +
:class:ArcaneZenithCognitiveCore.step_from_bio_rates. Per-frame
latency decays over the run as the pipeline warms up — the demo
reports 6 916 µs at frame 20 dropping to 2 945 µs at frame 100.
7.2 ArcaneZenith-coupled identity drift¶
Over the same 100-frame demo the attached
:class:ArcaneZenithCognitiveCore reports
identity_drift = 1.8625 at frame 100 (printed as "Final ArcaneZenith
identity drift: 1.8625" by the demo). Zero network bursts are detected
in the default 100-frame window; the drift tracks the novelty signal
produced by the closed loop.
7.3 HomeostaticPlasticity.update_threshold microbenchmark¶
| Input pattern | Result |
|---|---|
| target 10 Hz, observed 10 Hz, dt = 100 ms | new == 256 (no change) |
| target 10 Hz, observed 50 Hz, dt = 1000 ms, | new > 256 (raised) |
| τ_homeo = 1000 ms | |
| target 10 Hz, observed 1 Hz, dt = 1000 ms, | new < 256 (lowered) |
| τ_homeo = 1000 ms | |
| 10 000 Hz error for 10 s | saturates at max_q88 |
| 0 Hz for 10 s | saturates at min_q88 |
All five cases are enforced by the TestHomeostaticPlasticity test
group. The controller is pure integer arithmetic (subtraction,
multiplication, floor-division, clamp) — CPU cost well below one
microsecond per call.
7.4 Reproducer¶
# 7.1 + 7.2 end-to-end demo
MPLBACKEND=Agg python examples/14_bioware_closed_loop_demo.py
# 7.3 homeostatic controller
python -c "
from sc_neurocore.bioware.bioware import HomeostaticPlasticity
hp = HomeostaticPlasticity(target_rate_hz=10.0, tau_homeo_ms=1000.0)
print(hp.update_threshold(256, observed_rate_hz=10.0, dt_ms=100.0)) # 256
print(hp.update_threshold(256, observed_rate_hz=50.0, dt_ms=1000.0)) # >256
print(hp.update_threshold(256, observed_rate_hz=1.0, dt_ms=1000.0)) # <256
"
The demo prints [3] Experiment complete in 0.69s. on the
reference host.
8. Citations¶
- Bi, G.-Q. & Poo, M.-M. (1998). Synaptic modifications in
cultured hippocampal neurons: dependence on spike timing, synaptic
strength, and postsynaptic cell type. Journal of Neuroscience
18(24): 10464–10472. — Exponential pair-based STDP used by
:class:
BiologicalSTDP. - Bienenstock, E. L., Cooper, L. N., Munro, P. W. (1982).
Theory for the development of neuron selectivity: orientation
specificity and binocular interaction in visual cortex. Journal
of Neuroscience 2(1): 32–48. — BCM metaplasticity used by
:class:
BCMPlasticity. - Donoho, D. L. & Johnstone, I. M. (1994). Ideal spatial
adaptation by wavelet shrinkage. Biometrika 81(3): 425–455. —
MAD / 0.6745 robust σ estimator used by
:class:
SpikeDetector.estimate_noise. - Kagan, B. J., Kitchen, A. C., et al. (2022). In vitro neurons
learn and exhibit sentience when embodied in a simulated
game-world. Neuron 110(23): 3952–3969.e8. — Reference closed-loop
MEA-opto experiment motivating :class:
BioHybridSession. - Lewicki, M. S. (1998). A review of methods for spike sorting:
the detection and classification of neural action potentials.
Network: Computation in Neural Systems 9(4): R53–R78. — Classical
PCA-based spike sorter; direct antecedent of
:class:
SpikeSorter. - Turrigiano, G. G. (2012). Homeostatic synaptic plasticity:
local and global mechanisms for stabilizing neuronal function.
Cold Spring Harbor Perspectives in Biology 4(1): a005736. —
Biological reference for the slow homeostatic timescales modelled
by :class:
HomeostaticPlasticity.
9. Limitations¶
- SpikeSorter needs scikit-learn. Without it,
fitraises a clearImportErrorwith a pointer to the[bioware]extras. The empty-input path is a no-op and does not require sklearn. - PCA + KMeans is a minimal baseline. Production spike-sorting should use SpikeInterface, Kilosort 3+, or MountainSort. The SC-NeuroCore sorter exists as a closed-loop demo.
- No real-time FPGA coupling inside this module. The transcoder
produces AER events suitable for the PYNQ-Z2 hardware, but the
actual streaming to the FPGA is caller-owned (see
hdl/). - Q8.8 homeostatic controller is proportional only. A full
PID controller would need integral and derivative state; the
current single-step update is tuned to the slow
tau_homeoregime where P is sufficient (Turrigiano 2012). - BioHybridFrameResult mapping view is read-only.
in,[key], andkeys()work;result[key] = valueraises. Mutate the dataclass fields directly for reply-time updates.
Reference¶
- Module:
src/sc_neurocore/bioware/bioware.py. - Tests:
tests/test_bioware/test_bioware.py(40+ tests incl. TestMEAConfig, TestSpikeDetector, TestMEAToAERTranscoder, TestAERToSCConverter, TestSCToOptoEncoder, TestBiologicalSTDP, TestBCMPlasticity, TestCultureHealth, TestBioHybridSession, TestRefractoryPeriod, TestOptoSafety, TestEdgeCases, TestSpikeSorter, TestLFPExtraction, TestLatencyBudget, TestPharmModel, TestMultiWellPlate, TestNetworkBurstDetection, TestArtifactRejection, TestBioAuditLog, TestBitstreamRateDecoder, TestHomeostaticPlasticity, TestBioHybridFrameResult, TestMEAFitnessHook). - Demo:
examples/14_bioware_closed_loop_demo.py(100-frame end-to-end closed loop with ArcaneZenith + PCA spike sorting). - Cross-references: :doc:
arcane_zenith(zenith_coreattachment), :doc:evo_substrate(mea_fitness_hook).
sc_neurocore.bioware.bioware
¶
Interface primitives for living neural cultures and organoids.
Bridges biological neural activity (from MEA recordings) to SC bitstreams and vice-versa. Enables closed-loop bio-hybrid experiments where:
- MEA → AER: Spike-sorts multi-electrode array data into AER events
compatible with
sc_aer_encoder.v/sc_aer_router.v. - AER → SC: Converts AER events into SC bitstreams for deterministic stochastic processing.
- SC → Optogenetics: Encodes SC output as optical pulse sequences for closed-loop stimulation.
- Biological Plasticity: STDP/BCM adapters bridging biological time constants (ms) to SC clock rates (MHz).
Compatible with:
- hdl/sc_aer_encoder.v — AER spike encoding
- hdl/sc_aer_router.v — AER spike routing
- analysis/spike_stats — spike train analysis
- profiling/spike_profiler.py — spike rate profiling
MEALayout
¶
Bases: Enum
Standard MEA electrode layouts.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
55 56 57 58 59 60 61 62 | |
MEAConfig
dataclass
¶
Multi-electrode array configuration.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
DetectedSpike
dataclass
¶
One detected spike event from MEA data.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
92 93 94 95 96 97 98 99 100 | |
SpikeDetector
dataclass
¶
Threshold-based spike detector for MEA voltage traces.
Uses adaptive threshold: threshold = mean ± sigma * noise_estimate where noise_estimate = median(|x|) / 0.6745 (robust RMS). Supports configurable refractory period to prevent double-counting.
Source code in src/sc_neurocore/bioware/bioware.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 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 | |
estimate_noise(voltage_data)
¶
Estimate per-channel noise from voltage data.
Uses median absolute deviation (MAD) for robustness against spikes. voltage_data: shape (num_samples, num_channels)
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
116 117 118 119 120 121 122 123 124 | |
detect(voltage_data, snippet_ms=2.0)
¶
Detect spikes in multi-channel voltage data.
voltage_data: shape (num_samples, num_channels) Returns list of DetectedSpike events.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
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 | |
AEREvent
dataclass
¶
Address-Event Representation packet.
Compatible with sc_aer_encoder.v format:
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
189 190 191 192 193 194 195 196 197 198 199 200 | |
MEAToAERTranscoder
dataclass
¶
Converts MEA spike events to AER events for hardware.
Maps biological electrode channels to AER neuron IDs, converting real-time timestamps to hardware clock ticks.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
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 | |
transcode(spikes, t_start_s=0.0)
¶
Convert detected spikes to AER events.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
AERToSCConverter
dataclass
¶
Converts AER event streams to SC bitstreams.
Uses a time-windowed rate code: count events per neuron per window, then LFSR-encode the resulting firing probabilities.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
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 | |
convert(events)
¶
Convert AER events to per-neuron SC bitstreams.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
257 258 259 260 261 262 263 264 265 266 267 268 269 270 | |
StimProtocol
¶
Bases: Enum
Optogenetic stimulation protocols.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
290 291 292 293 294 295 296 | |
OptogeneticPulse
dataclass
¶
One optical stimulation pulse.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
299 300 301 302 303 304 305 306 307 | |
SCToOptoEncoder
dataclass
¶
Encodes SC bitstream output as optogenetic pulse sequences.
Maps SC bitstream density to optical stimulation intensity, enabling closed-loop feedback from in-silico → biological. Enforces total power budget for tissue safety.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
encode(bitstreams, t_start_ms=0.0)
¶
Convert SC bitstreams to optogenetic pulses.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
BiologicalSTDP
dataclass
¶
Spike-Timing-Dependent Plasticity adapter for bio-hybrid loops.
Bridges biological STDP time constants (∼20 ms) to SC clock rates (MHz) via a time-scaling factor. Computes ΔW from pre/post spike timing in biological time, then converts to Q8.8 weight updates for the SC domain.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | |
compute_dw(dt_ms)
¶
Compute weight change from spike timing difference.
dt_ms = t_post - t_pre (positive = potentiation, negative = depression)
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
379 380 381 382 383 384 385 386 387 388 | |
update_weight(current_q88, dt_ms)
¶
Update Q8.8 weight from spike timing.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
390 391 392 393 394 395 | |
BCMPlasticity
dataclass
¶
Bienenstock-Cooper-Munro plasticity adapter.
Implements sliding-threshold BCM rule where the modification threshold θ tracks the postsynaptic firing rate. Converts biological firing rates to Q8.8 weight deltas.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 | |
update_theta(post_rate_hz, dt_ms)
¶
Update the sliding threshold from postsynaptic activity.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
413 414 415 416 417 418 | |
compute_dw(pre_rate_hz, post_rate_hz)
¶
BCM weight change: ΔW = η * x * y * (y - θ).
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
420 421 422 | |
CultureHealth
dataclass
¶
Monitor organoid/culture viability from MEA activity.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | |
assess(spike_counts, duration_s)
¶
Assess culture health from spike activity.
spike_counts: per-channel spike counts over duration_s
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | |
BioHybridFrameResult
dataclass
¶
Strictly typed output packet detailing a full closed-loop step.
Behaves both as a dataclass (result.round) and, for backward
compatibility with pre-dataclass callers, as a mapping view of its
fields (result["round"], "latency_us" in result,
dict(result)). The mapping surface is read-only.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 | |
BioHybridSession
dataclass
¶
Manages a complete bio-hybrid experiment session.
Orchestrates: MEA recording → spike detection → AER transcoding → SC processing → optogenetic feedback → plasticity update.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 | |
process_frame(voltage_data, t_start_s=0.0, stim_times_s=None)
¶
Process one MEA data frame through the full pipeline.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 | |
SpikeSorter
dataclass
¶
Production-ready spike sorter utilizing PCA feature extraction and K-Means clustering.
Extracts the dominant principal components from the input raw waveforms, and cleanly
separates units. Handles missing datasets explicitly natively. Requires scikit-learn to execute correctly.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 | |
fit(spikes)
¶
Fit PCA and KMeans models sequentially on available waveforms.
Silently no-ops (leaves _pca/_kmeans as None) when
fewer than num_units waveforms are present — sklearn is only
imported in the path that actually needs it, so empty or
amplitude-only spike lists don't require scikit-learn.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 | |
assign(spikes)
¶
Assign cluster IDs based on PCA feature projections.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 | |
LFPBand
dataclass
¶
Frequency band definition for LFP extraction.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
677 678 679 680 681 682 683 | |
LatencyBudget
dataclass
¶
Tracks and enforces closed-loop latency requirements.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 | |
record(latency_us)
¶
Record a latency measurement. Returns True if within budget.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
731 732 733 734 735 736 737 | |
PharmModel
dataclass
¶
Simulates effect of pharmacological agents on spike rate.
Models excitatory (e.g., bicuculline) or inhibitory (e.g., TTX) agents as gain factors on firing rate.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 | |
modulate_spikes(spike_counts, t_current_s)
¶
Modulate spike counts by pharmacological gain.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
783 784 785 786 | |
modulate_spike_events(spikes, t_current_s)
¶
Apply pharmacological rate gain to spike events.
Inhibitory gains deterministically thin events across the observed response span instead of truncating the head of the frame. Excitatory gains preserve observed events and insert synthetic events inside the observed temporal support, using nearest observed spikes as channel, unit, amplitude, and waveform templates.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 | |
WellConfig
dataclass
¶
One well in a multi-well MEA plate.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
859 860 861 862 863 864 865 866 867 868 869 870 | |
MultiWellPlate
dataclass
¶
Multi-well plate (e.g., 6/24/48/96-well MEA plate).
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 | |
NetworkBurst
dataclass
¶
Detected network-wide synchronised burst event.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
905 906 907 908 909 910 911 912 | |
ArtifactRejector
dataclass
¶
Blanks stimulation artifacts from voltage data.
Zeros the voltage trace in a window around each stimulation onset.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 | |
blank(voltage_data, stim_times_s, sample_rate_hz)
¶
Return voltage data with stimulus artifacts blanked.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 | |
BioAuditEntry
dataclass
¶
One audit entry for a bio-hybrid session.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 | |
BioAuditLog
dataclass
¶
Regulatory-grade audit log for bio-hybrid experiments.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 | |
checksum()
¶
SHA-256 of log contents for tamper detection.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 | |
HomeostaticPlasticity
dataclass
¶
Intrinsic excitability scaling to maintain target firing rate.
Implements homeostatic plasticity: if a neuron fires too fast, reduce its excitability (threshold up); too slow, increase it. Operates on Q8.8 threshold values.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 | |
update_threshold(current_q88, observed_rate_hz, dt_ms)
¶
Adjust threshold to drive firing rate toward target.
Proportional homeostatic controller on a Q8.8 fixed-point
threshold. alpha = dt_ms / tau_homeo_ms is the integration
weight over the time step; the rate error (observed − target)
is scaled by alpha·256 so that a 1 Hz error integrated over
one full time-constant shifts the threshold by 1.0 Q8.8 unit
(i.e. by 256 in integer representation). Result clamped to
[min_threshold_q88, max_threshold_q88].
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 | |
extract_lfp_power(voltage_data, sample_rate_hz, bands=None)
¶
Extract per-channel power in each LFP band.
Uses FFT-based power spectral density estimation. Returns dict of band_name → per-channel power array.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 | |
detect_network_bursts(spikes, bin_width_s=0.01, threshold_sigma=3.0, min_channels=3)
¶
Detect network-wide synchronised bursts.
Bins spikes in time, detects bins with activity > threshold_sigma above the mean, and requires participation from ≥ min_channels.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 | |
decode_bitstream_rate(bitstreams, sc_clock_hz=1000000.0)
¶
Decode SC bitstreams back to biological firing rates (Hz).
Interprets popcount/length as probability, scales by SC clock to get equivalent biological firing rate.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 | |
mea_fitness_hook(detected_spikes, target_rate=10.0, *, duration_s=None, stimulus_time_s=None, measured_latency_ms=None)
¶
Organism fitness metrics derived from MEA response dynamics.
Designed to plug into the evo_substrate
ReplicationEngine(metrics_fn=mea_fitness_hook) — returns the
{"accuracy", "energy_mw", "latency_ms"} triple the engine scores.
Accuracy is a bounded distance to the target mean per-channel firing
rate when duration_s is supplied, or to the legacy per-channel
spike count when it is omitted. energy_mw remains the documented
spike-count proxy (0.5 mW / spike). latency_ms is either a caller
supplied closed-loop measurement, the first response latency after
stimulus_time_s, or the first spike timestamp relative to frame
start.
Source code in src/sc_neurocore/bioware/bioware.py
| Python | |
|---|---|
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 | |