Ad Code

OpenBioz Labs

Indian Biotech Research & Development Company

Innovating with Intelligence Open Biointell

Biological Neural Network API

CL API · Real-time closed-loop BNN · Research article
Research Article · Cortical Labs

CL API: Real‑Time Closed‑Loop Interactions with Biological Neural Networks

A contract‑based Python interface enabling sub‑millisecond, deterministic stimulation and recording for in vitro neural networks. Declarative semantics, transactional admission via StimPlan, microsecond‑scale closed‑loop control, and full observability.

D. Hogan, A. Doherty, B. K. Khoo, J. Zhou, R. Salib, J. Stewart, K. Lawson, A. Loeffler, B. J. Kagan Cortical Labs 2026 · arXiv:2602.11632v1

Abstract & motivation

Biological neural networks (BNNs) are increasingly explored for their rich dynamics, parallelism, and adaptive behaviour — and as a novel computing substrate in Synthetic Biological Intelligence (SBI) and Organoid Intelligence (OI). BNNs can only function as reliable information‑processing systems if inputs are delivered in a temporally and structurally consistent manner.

In practice this requires stimulation with precisely controlled structure, microsecond‑scale timing, multi‑channel synchronisation, and the ability to observe and respond to neural activity in real time. Existing approaches face a fundamental trade‑off: low‑level hardware mechanisms impose prohibitive complexity for rapid iteration, while high‑level software sacrifices temporal and structural control — undermining consistency and reproducibility, particularly in closed‑loop experiments.

The Cortical Labs Application Programming Interface (CL API) enables real‑time, sub‑millisecond closed‑loop interactions with BNNs. Taking a contract‑based API design approach, it provides precise stimulation semantics, transactional admission, deterministic ordering, and explicit synchronisation guarantees — exposed through a declarative Python interface that lets non‑expert programmers express complex stimulation and closed‑loop behaviour without managing low‑level scheduling or hardware details.

“A key focus has been using these biological systems as a novel computing substrate … BNNs display rich parallel dynamics and the capacity for robust synaptic plasticity — and functional connectivity changes unavailable to silicon von Neumann architectures.”

Three primary contributions

  1. A formal programming contract for real‑time, closed‑loop interaction with BNNs, specifying timing, ordering, synchronisation, and failure semantics independent of implementation.
  2. A declarative programming model that exposes this contract to users, enabling precise specification of stimulation and recording behaviour without low‑level scheduling or hardware control.
  3. An empirical demonstration of feasibility, via a reference implementation (CL1) showing that the proposed semantics can be satisfied in practice under real‑time and hardware resource constraints.

The three pillars of BNN interaction

  • Wetware — ethical, scalable, specific neural cells (differentiated pluripotent stem cells).
  • Hardware — viable interfaces maintaining cell health (e.g. MEAs, CMOS arrays).
  • Software — real‑time frameworks for closed‑loop algorithms. This paper addresses the third pillar.

Design pillars

Ease of use: Python‑first, declarative, modular, transparent — minimising cognitive load for interdisciplinary researchers. Precision: temporal fidelity (μs‑scale determinism) and real‑time latency within the causal window of the biological network.

The CL API contract — guarantees, assumptions, constraints

A programming contract is a precise agreement between a software interface and its users about how operations behave — not how the system is implemented internally, but the guarantees users may rely on and the assumptions under which they hold.

ItemContract areaGuarantees / assumptions / constraints
5.1 Real‑time closed‑loop execution with defined temporal semantics Real‑time means defined temporal correctness, not merely low average latency. Users may assume: (i) operations execute with bounded latency suitable for closed‑loop control; (ii) temporal behaviour is defined at the API level, including meaning of timestamps, ordering, completion; (iii) transitions between requested stimulation frequencies are seamless; (iv) correctness is preserved under concurrency and load.
5.2 Declarative specification of intent Timing guarantees apply under realistic experimental conditions, including overlapping stimulation, concurrent recording, and closed‑loop feedback; the API prioritises semantic correctness over best‑effort execution.
5.3 Deterministic ordering, synchronisation, start‑time semantics (i) recording, stimulation, and closed‑loop behaviour are expressed as declarative requests; (ii) users do not manage low‑level scheduling or I/O pumping; (iii) the system enforces ordering, timing, and correctness per the contract.
5.5 Semantic consistency across simulation and hardware (i) same API calls imply same ordering, timing, correctness guarantees; (ii) simulation and hardware differ only in physical timing resolution and latency, not in meaning; (iii) simulation is deterministic and authoritative w.r.t. API semantics; (iv) simulation enforces API‑level correctness but may not enforce all hardware capacity constraints — a transaction accepted in simulation may be rejected on hardware when limits are exceeded.
5.6 Transparency, auditability, reproducibility (i) timing, ordering, and execution outcomes are observable through API‑visible timestamps, events, and return values; (ii) timestamps provide a consistent basis for post‑hoc analysis; (iii) execution behaviour can be inspected and reproduced under controlled conditions.
5.7 Scope & non‑guarantees The CL API does not guarantee: (i) absolute start‑time execution without explicit synchronisation; (ii) zero latency or zero jitter; (iii) deterministic biological responses; (iv) unlimited scaling without resource contention; (v) that hardware‑specific resource limits are exposed or fixed across configurations; (vi) that the simulator reproduces all hardware‑specific resource limits.
Reliability over absolute accuracy. BNNs lack a stable ground truth outside reductionist patch‑clamp experiments. Population‑level MEA recordings are influenced by electrode distance, extracellular matrix density, and cell maturity — making absolute accuracy hard to standardise. The CL API therefore prioritises reliability: whether a pulse is 1.1 μA or 1.2 μA is secondary to ensuring it is identical across every trial.

CL1 reference implementation

The CL1 tightly integrates a user‑space library, a Linux kernel driver, and an FPGA to execute Python CL API calls with negligible jitter and latency measured in microseconds. A compatible simulator supports development without physical hardware.

~3 μs
stim call (user‑space)
80–120 μs
stim onset (idle ch.)
40 μs
hardware timing frame
50 kHz
stim base frequency
25 kHz
max loop rate
33–34 μs
loop budget @ 25 kHz
≤ 0.2%
freq. error (≤200 Hz)
~5 s
jitter recovery window

System stack

  • User‑space Python library — declarative API surface.
  • Linux kernel driver — deterministic I/O scheduling.
  • FPGA timing engine — microsecond‑accurate waveform generation and sampling.

Design principles in practice

Ease of use

Python is the standard language for data science and machine learning; the API integrates with existing tools for processing, debugging, and visualisation. Intuitive signatures and a declarative style abstract away execution mechanisms so researchers focus on experimental logic.

Modularity

In vitro BNNs involve significant uncertainty — far more is unknown than known. The API provides basic computational building blocks that can be assembled to meet unforeseen requirements, supporting rapid iteration without platform changes.

Transparency

Execution semantics are observable: full visibility into how and when commands execute — critical for distinguishing biological artefacts from system behaviours.

Precision

Temporal fidelity: STDP‑type mechanisms rely on ms‑scale pre/post correlations, so stimulation waveforms are generated with μs‑scale determinism. Real‑time latency: the round‑trip (read spike → compute → stimulate) must rival natural synaptic delays, so the system can act as artificial nodes within the biological network rather than delayed observers.

Stimulation semantics

Stimulation is specified by a ChannelSet for electrode selection, a StimDesign defining per‑phase duration, electrical current, and polarity, and optionally a BurstDesign to request repetition as a burst of events at a fixed frequency.

Single stim & burst

import cl

with cl.open() as neurons:
    # stimulate channels 20, 42, 51, 60
    channel_set = cl.ChannelSet(20, 42, 51, 60)
    # bi-phasic: 200us -2.0uA / 200us +2.0uA
    stim_design = cl.StimDesign(200, -2.0, 200, 2.0)

    # single stimulation event
    neurons.stim(channel_set, stim_design)

    # or burst of 20 stims at 37.9 Hz
    burst_design = cl.BurstDesign(20, 37.9)
    neurons.stim(channel_set, stim_design, burst_design)

Lead time & ISI encoding

# Increase stim interval by 2.5 ms
# each time until 100 ms
for lead_time_us in range(
        5000, 100000 + 1, 2500):
    neurons.stim(
        channel_set,
        stim_design,
        lead_time_us=lead_time_us)

Calls to Neurons.stim(...) can take as little as 3 μs; active stimulation begins 80–120 μs after that if the requested channels are idle. The minimum 80 μs lead time is a trade‑off between latency and control — per‑pulse current control is gained at the cost of 80 μs of latency. Additional lead time can be requested by overriding lead_time_us.

Inter‑stimulus interval encoding. Ongoing stimulation can be atomically interrupted and replaced on specified channels via interrupt_then_stim(...). Interruptions take effect only at well‑defined stimulus boundaries, so no spurious transitional ISI is introduced between successive regimes.

Burst frequency quantisation

The CL1 uses a fixed 50 kHz stimulation base frequency (minimum period 20 μs), so burst frequencies are approximated by the nearest integer multiple of 20 μs. Within the CL1 simulation limit of 200 Hz, the maximum error deviation from a requested frequency is 0.2%.

Figure 1 (paper): Absolute error (top) and percentage error (bottom) to the closest representable frequency vs. requested frequency. Error grows monotonically toward 200 Hz but stays ≤ 0.2%.
Burst frequency error is bounded by the 20 μs quantisation step; below ~100 Hz, error is negligible (< 0.05%).

Synchronisation & stimulation plans

Per‑channel queues & sync(...)

Each channel maintains an independent stimulation queue. When a queue is empty, a newly requested operation begins as soon as it becomes visible to the timing engine; otherwise it is appended to the queue. Without coordination, precise multi‑channel temporal alignment is non‑trivial.

Neurons.sync(...) provides an explicit coordination barrier: it delays subsequently queued stimulation on the specified channels until all prior activity on each has completed — guaranteeing simultaneous onset across channels regardless of queue depth or history.

Neurons.stim(...) automatically introduces synchronisation when operating on a multi‑channel ChannelSet. Explicit sync(...) is needed only between otherwise unrelated channels.

Scenario comparison (Figure 2)

Scenario A — without synchronisation:
Two independent, non‑overlapping ChannelSet instances. Both queues are initially empty, so stimulation on all channels begins simultaneously.
Channels 12/18 (set 1) and 20/42 (set 2) start together by happenstance of empty queues.
Scenario B — with explicit synchronisation:
A Neurons.sync(channel_set_1 | channel_set_2) call between the two stim calls forces the second stimulation to wait for the first to finish.
Set 2 begins only after set 1 completes — a well‑defined ordering guarantee.

Stimulation plans (StimPlan)

Even the simplest Neurons.stim(...) takes ~3 μs in user space, and newly submitted operations become visible to the hardware timing engine at fixed 40 μs frame intervals. Successive stim calls may therefore be admitted in different frames and not begin at exactly the same time.

StimPlan allows multiple related requests to be admitted transactionally (all‑or‑none, never partial) and become visible simultaneously. Combined with inter‑channel synchronisation, plans give precise control over which stimulation is active on each channel and when activity begins relative to other activity in the plan.

# Two disjoint channel groups with distinct designs
channel_set_1 = cl.ChannelSet(20, 42, 51, 60)
stim_design_1 = cl.StimDesign(200, -2.0, 200, 2.0)
burst_design_1 = cl.BurstDesign(20, 40)

channel_set_2 = cl.ChannelSet(2, 6, 12, 18)
stim_design_2 = cl.StimDesign(100, -1.5, 100, 1.5)
burst_design_2 = cl.BurstDesign(10, 20)

all_target_channels = channel_set_1 | channel_set_2

with cl.open() as neurons:
    stim_plan = neurons.create_stim_plan()

    # declarative interruption (atomic with plan visibility)
    stim_plan.channels_to_interrupt = all_target_channels

    # block until interruption complete & channels ready
    stim_plan.sync(all_target_channels)

    # non-overlapping sets → simultaneous onset guaranteed
    stim_plan.stim(channel_set_1, stim_design_1, burst_design_1)
    stim_plan.stim(channel_set_2, stim_design_2, burst_design_2)

    # submit ASAP
    stim_plan.run()

    # re-run the same plan 2 seconds later
    stim_plan.run(neurons.timestamp() +
                  (2 * neurons.get_frames_per_second()))

In this example, channels 2/6/12/18 are stimulated with biphasic 1.5 μA, 100 μs pulses, while channels 20/42/51/60 receive 2 μA, 200 μs pulses. Because each group has a distinct BurstDesign, the two sets operate at different stimulation frequencies — all admitted atomically.

A plan may be executed multiple times (once per run()) and scheduled for a specific future timestamp via run(at_timestamp=...). Interruption is expressed declaratively via channels_to_interrupt — plans can interrupt existing activity only at the moment they become visible, keeping interruption + stimulation atomic at a well‑defined boundary.

Real‑time loops & spike detection

Neurons.loop(...) provides a time‑driven execution context in which detected action potentials (spikes) are surfaced to user code at a fixed iteration frequency of up to 25 kHz. Each iteration corresponds to a well‑defined timing frame, allowing user logic to observe activity and issue responses with bounded, repeatable latency.

Observing spikes

with cl.open() as neurons:
  for tick in neurons.loop(
        ticks_per_second=1000,
        stop_after_seconds=5):
    for spike in tick.analysis.spikes:
      print(spike)

# Spike(timestamp=2707168587, channel=52)
# Spike(timestamp=2707168645, channel=58)
# Spike(timestamp=2707168737, channel=32)

All spikes detected since the previous iteration are exposed — no events are missed even if multiple spikes occur within a single timing frame.

Spike → stim (25 kHz)

with cl.open() as neurons:
  for tick in neurons.loop(
        ticks_per_second=25000,
        stop_after_ticks=25000):
    for spike in tick.analysis.spikes:
      # respond on same channel
      neurons.stim(spike.channel, stim_design)

The Spike object

PropertyData
timestampTimestamp of the sample that triggered detection
channelWhich channel the spike was detected on
samplesNumPy array of 75 floating‑point μV sample values around the timestamp

The samples array is mean‑centred per channel at detection time (removing the instantaneous baseline while preserving waveform shape), converted to physical units (μV). It contains 1 ms of samples preceding the detection timestamp and 2 ms beginning at the timestamp. Sample data is populated lazily; accessing Spike.samples before the full post‑detection window is acquired blocks for up to 2 ms. Lazy loading is only supported within ~5 s of detection.

tick.analysis.stims contains Stim objects recording stimulation that began during the previous tick, allowing closed‑loop algorithms to interleave observed spikes and issued stims in a single time‑ordered log.

Jitter detection, budgets & recovery

Per‑iteration deadline enforcement

At 25 kHz, each loop iteration corresponds to a 40 μs timing frame. After fixed system overheads, the user‑level loop body has an effective budget of approximately 33–34 μs.

# Consume ~33 us → passes
for tick in neurons.loop(ticks_per_second=25000):
  wait_until = time_ns() + 33_000
  while time_ns() < wait_until: pass

# Consume ~35 us → TimeoutError
# Loop fell behind by 1 frame (40 us) at iteration 8.

The jitter subsystem enforces a strict per‑iteration deadline relative to newly sampled electrode data — it does not evaluate average execution time. A missed deadline raises TimeoutError rather than allowing silent jitter accumulation.

recover_from_jitter(...)

For experiments that must occasionally perform a blocking operation (e.g. a remote service call), the loop can tolerate a bounded lapse without triggering a jitter error — explicitly opt‑in, preserving well‑defined temporal semantics.

def recovery_callback(tick):
  print(f"Iteration {tick.iteration} skipped")

for tick in neurons.loop(100, stop_after_ticks=10):
  if tick.iteration == 2:
    sleep(3 * SECONDS_PER_TICK)
    tick.loop.recover_from_jitter(
        handle_recovery_tick=recovery_callback)

The internal iteration counter advances rapidly to realign with the frame clock; skipped iterations are forwarded to the callback. timeout_seconds (default 5 s) acts as a watchdog, and recovery is limited by a finite ~5 s retrospective data window.

Recovery constraints. The handle_recovery_tick callback must remain computationally lightweight — if its execution time approaches the nominal tick interval, the recovery process cannot close the latency gap and resynchronisation fails.

Recording, data streams & timestamps

The CL1 recording subsystem produces HDF5 files capturing detected spikes, stimulation events, application‑defined time series, and a complete record of raw electrode samples. An application initiates recording with a single API call; the system transparently pumps and schedules the recording I/O path — the application is never responsible for explicit pumping.

One‑call recording

with cl.open() as neurons:
  recording = neurons.record()
  # arbitrary blocking foreground work
  game.run(neurons)
  recording.stop()
  print(recording.file['path'])

Supports precise control over duration (stop_after_seconds), selective inclusion of data modalities, and bounded retrospective capture — enabling reproducible experiment reconstruction without entangling recording concerns with application control flow.

Named data streams

stream = neurons.create_data_stream(
    name='game_state',
    attributes={'score': 0})

ts = neurons.timestamp()
stream.append(ts + 0, {'x': 4, 'y': 9})
stream.append(ts + 1, np.array([2**64-1]))

stream.set_attribute('score', 1)

Each entry requires a unique, strictly increasing timestamp. Payloads may be arbitrary Python objects (dict, tuple, list, scalars, NumPy arrays). Attributes store only the most recent value.

Frame‑relative time base

All timestamps within a recording — spike times, stimulation events, data stream entries — are expressed as monotonically increasing frame indices relative to the start of the recording. This self‑contained reference lets recorded events be aligned and compared without relying on absolute or wall‑clock time.

from cl import RecordingView
recording = RecordingView("/data/recordings/...Recording.h5")

for timestamp, data in recording.data_streams.game_state.items():
    print(timestamp, data)

# 4461 {'x': 4, 'y': 9}
# 4462 [18446744073709551615 18446744073709551614 ...]

Application state, derived quantities, and annotations can be analysed alongside neural recordings using a common time base — with no custom parsing or synchronisation logic.

Simulation semantics

Programs written against the CL API exhibit consistent semantics across simulation and hardware execution. This supports reproducible development, testing, and validation independently of hardware availability.

What the simulator guarantees

  • Same API calls imply the same ordering, timing, and correctness guarantees.
  • Simulation and hardware differ only in physical timing resolution and latency — not in meaning.
  • Simulation is deterministic and authoritative with respect to API semantics.

Where simulation differs

  • Simulation enforces API‑level semantic correctness but may not enforce all hardware‑specific capacity constraints.
  • A transaction accepted in simulation may be rejected on hardware when limits are exceeded.
  • Capacity‑sensitive behaviour should always be validated on the target hardware.
80–120 μs
stimulation onset latency
25 kHz
max closed‑loop loop rate
≤ 0.2%
burst frequency error (≤200 Hz)
50 kHz
stimulation base frequency

Citation & selected references

Cite this article: Hogan, D., Doherty, A., Khoo, B. K., Zhou, J., Salib, R., Stewart, J., Lawson, K., Loeffler, A., & Kagan, B. J. (2026). CL API: Real-Time Closed-Loop Interactions with Biological Neural Networks. arXiv preprint arXiv:2602.11632v1.

Selected references (from 51 total)

  1. Kagan, B. J., et al. (2022). “In vitro neurons learn and exhibit sentience when embodied in a simulated game-world.” Neuron, 110(23), 3952–3969.e8. DOI: 10.1016/j.neuron.2022.09.001
  2. Kagan, B. J., et al. (2023). “The technology, opportunities, and challenges of Synthetic Biological Intelligence.” Biotechnology Advances, 68, 108233. DOI: 10.1016/j.biotechadv.2023.108233
  3. Kagan, B. J. (2025). “The CL1 as a platform technology to leverage biological neural system functions.” Nature Reviews Bioengineering. DOI: 10.1038/s44222-025-00340-3
  4. Smirnova, L., et al. (2023). “Organoid intelligence (OI): the new frontier in biocomputing and intelligence-in-a-dish.” Frontiers in Science, 1. DOI: 10.3389/fsci.2023.1017235
  5. Jimbo, Y., Robinson, H. P. C., & Kawana, A. (1998). “Strengthening of synchronized activity by tetanic stimulation in cortical cultures.” IEEE TBME, 45(11), 1297–1304. DOI: 10.1109/10.725326
  6. Shahaf, G., & Marom, S. (2001). “Learning in Networks of Cortical Neurons.” J. Neuroscience, 21(22), 8782–8788. DOI: 10.1523/JNEUROSCI.21-22-08782.2001
  7. Isomura, T., Kotani, K., & Jimbo, Y. (2015). “Cultured Cortical Neurons Can Perform Blind Source Separation According to the Free-Energy Principle.” PLOS Comput. Biol., 11(12), e1004643. DOI: 10.1371/journal.pcbi.1004643
  8. Cai, H., et al. (2023). “Brain organoid reservoir computing for artificial intelligence.” Nature Electronics, 6(12), 1032–1039. DOI: 10.1038/s41928-023-01069-w
  9. Habibollahi, F., et al. (2023). “Critical dynamics arise during structured information presentation within embodied in vitro neuronal networks.” Nature Communications, 14(1), 5287. DOI: 10.1038/s41467-023-41020-3
  10. Müller, J., Bakkum, D. J., & Hierlemann, A. (2013). “Sub-millisecond closed-loop feedback stimulation between arbitrary sets of individual neurons.” Frontiers in Neural Circuits, 6. DOI: 10.3389/fncir.2012.00121
  11. Newman, J. P., et al. (2013). “Closed-Loop, Multichannel Experimentation Using the Open-Source NeuroRighter Electrophysiology Platform.” Frontiers in Neural Circuits, 6. DOI: 10.3389/fncir.2012.00098
  12. Jordan, F. D., et al. (2024). “Open and remotely accessible Neuroplatform for research in wetware computing.” Frontiers in AI, 7, 1376042. DOI: 10.3389/frai.2024.1376042
  13. Lindell, T. A. E., et al. (2025). “Information Encoding and Decoding in In Vitro Neural Networks on Micro Electrode Arrays through Stimulation Timing.” Int. J. Unconventional Computing, 20(3), 155. DOI: 10.32908/ijuc.v20.300924
  14. Paszke, A., et al. (2019). “PyTorch: An Imperative Style, High-Performance Deep Learning Library.” arXiv:1912.01703. DOI: 10.48550/arXiv.1912.01703

Full reference list (51 entries) available in the paper, including foundational MEA, CMOS, optogenetic, and closed‑loop plasticity literature.

Conclusion

As work exploring in vitro neural cultures advances, reliable and widely accessible tools become critical. The CL API is not merely a high‑level wrapper over hardware mechanisms — it defines a clear, reliable contract governing the execution, timing, and coordination of neural recording and stimulation.

By formalising these guarantees, the CL API decouples experimental logic from implementation details: the “black box” of hardware execution is replaced by a transparent, predictable interface. The adoption of a rigorous execution contract is a necessary step toward addressing the reproducibility crisis in the field — transforming BNN research from bespoke, hardware‑dependent demonstrations into a rigorous, reproducible, and scalable discipline.

Equally important, these performance benefits are achieved in coordination with ease of use, modularity, and transparency. Democratising access to BNNs via the CL API empowers a broader spectrum of scientists and engineers — enhancing reproducibility, catalysing novel developments, accelerating discovery, and fostering multidisciplinary collaboration.

Cortical Labs · CL API research summary · cream / light brown / burnt orange · content distilled from arXiv:2602.11632v1