Introduction to braintools.input#

braintools.input builds the time series that drive a simulation: injected currents, stimulation protocols, and noise. Every generator returns an array with one entry per simulation step, so the result can be fed to a model step by step.

The module offers the same generators in two styles:

Functional API

Composable API

Names

lower case: step, sinusoidal, ou_process, …

capitalized: Step, Sinusoidal, OUProcess, …

Call

returns the array immediately

returns an Input object; calling the object returns the array

Combining

NumPy operations on arrays

operators (`+ - * / &

Best for

one-off signals

protocols built from parts, reused or varied

This tutorial covers what both styles share: the time step, array length, units, and how to feed an input into a model.

1. Setup#

import brainstate
import brainunit as u
import matplotlib.pyplot as plt
import numpy as np

import braintools

2. The Time Step Comes from brainstate.environ#

Generators do not take a dt argument; they read it from brainstate.environ. Set it globally with brainstate.environ.set(dt=...), or temporarily with the brainstate.environ.context(dt=...) context manager. An input of duration \(T\) has \(\lceil T / dt \rceil\) samples, and sample \(i\) belongs to time \(i \cdot dt\).

brainstate.environ.set(dt=0.1 * u.ms)

ramp = braintools.input.ramp(0.0, 1.0, 50 * u.ms)
print(f"dt = 0.1 ms, duration 50 ms -> {ramp.shape[0]} samples")

with brainstate.environ.context(dt=0.5 * u.ms):
    ramp_coarse = braintools.input.ramp(0.0, 1.0, 50 * u.ms)
print(f"dt = 0.5 ms, duration 50 ms -> {ramp_coarse.shape[0]} samples")
dt = 0.1 ms, duration 50 ms -> 500 samples
dt = 0.5 ms, duration 50 ms -> 100 samples

The time axis for plotting is therefore np.arange(n) * dt. A small helper used throughout:

def time_axis(signal, dt=None):
    # Time of every sample in ms.
    dt = brainstate.environ.get_dt() if dt is None else dt
    return np.arange(len(signal)) * dt.to_decimal(u.ms)

3. First Inputs: Both APIs Give the Same Array#

step(amplitudes, step_times, duration) holds each amplitude from its start time until the next start time (the last one until the end). Note that step_times are start times, not durations.

amplitudes = [0.0, 0.5, 1.0, 0.0]
starts = [0, 50, 100, 150] * u.ms

functional = braintools.input.step(amplitudes, starts, duration=200 * u.ms)
composable = braintools.input.Step(amplitudes, starts, duration=200 * u.ms)
print(type(composable).__name__, "->", composable().shape)
print("identical arrays:", bool(np.array_equal(functional, composable())))

fig, ax = plt.subplots(figsize=(8, 2.5))
ax.plot(time_axis(functional), functional)
ax.set_xlabel("time (ms)")
ax.set_ylabel("amplitude")
plt.show()
Step -> (2000,)
identical arrays: True
../_images/2de645cb68ea04e076c1b02e28704b820a7bf49332ee517b78a6634955438c78.png

4. Units#

Amplitudes may be plain numbers (a dimensionless signal) or brainunit quantities. With quantities, the result carries the unit, compatible units are converted, and incompatible ones raise an error instead of producing a silently wrong current.

small = braintools.input.Constant([(100 * u.pA, 20 * u.ms)])
medium = braintools.input.Constant([(2 * u.nA, 20 * u.ms)])
large = braintools.input.Constant([(0.01 * u.uA, 20 * u.ms)])

for name, inp in [("100 pA", small), ("2 nA", medium), ("0.01 uA", large)]:
    print(f"{name:8s} -> {inp()[0].to_decimal(u.nA):.3f} nA")

print("100 pA + 2 nA =", (small + medium)()[0])

try:
    (small + braintools.input.Constant([(1 * u.mV, 20 * u.ms)]))()
except u.UnitMismatchError as exc:
    print("current + voltage ->", type(exc).__name__)
100 pA   -> 0.100 nA
2 nA     -> 2.000 nA
0.01 uA  -> 10.000 nA
100 pA + 2 nA = 2100. pA
current + voltage -> UnitMismatchError

5. Feeding an Input into a Model#

An input array is indexed by step inside the simulation loop. Below, a leaky integrate-and-fire neuron

\[\tau_m \frac{dV}{dt} = -(V - E_L) + R\, I(t), \qquad V \ge V_{th} \Rightarrow V \leftarrow V_{reset}\]

is driven by a current step and by a slow sinusoid, using forward Euler with the same dt that generated the input.

def simulate_lif(current, tau=20 * u.ms, R=100 * u.Mohm, E_L=-70 * u.mV, V_th=-50 * u.mV, V_reset=-70 * u.mV):
    dt = brainstate.environ.get_dt()
    V = E_L
    trace, spikes = [], []
    for i, I in enumerate(current):
        V = V + dt / tau * (-(V - E_L) + R * I)
        if V >= V_th:
            spikes.append(i * dt)
            V = V_reset
        trace.append(V.to_decimal(u.mV))
    return np.array(trace), spikes


step_current = braintools.input.Step([0, 0.3, 0] * u.nA, [0, 50, 250] * u.ms, duration=300 * u.ms)
sine_current = braintools.input.Sinusoidal(0.3 * u.nA, 5 * u.Hz, 300 * u.ms) + 0.15 * u.nA

fig, axes = plt.subplots(2, 2, figsize=(11, 4.5), sharex=True)
for col, (name, inp) in enumerate([("step", step_current), ("sinusoid + offset", sine_current)]):
    current = inp()
    v, spikes = simulate_lif(current)
    t = time_axis(current)
    axes[0, col].plot(t, current.to_decimal(u.nA))
    axes[0, col].set_title(name)
    axes[0, col].set_ylabel("I (nA)")
    axes[1, col].plot(t, v)
    axes[1, col].set_ylabel("V (mV)")
    axes[1, col].set_xlabel("time (ms)")
    print(f"{name:18s}: {len(spikes)} spikes")
fig.tight_layout()
plt.show()
step              : 9 spikes
sinusoid + offset : 10 spikes
../_images/433687b1134f9061c3c2e8f9480b68dabbe220f4481872d2a857122ebcbb866b.png

With \(R I = 30\) mV the step drives \(V\) above threshold (20 mV above rest), so the neuron fires regularly during the step; during the sinusoid it fires only near the peaks, where \(R I\) exceeds 20 mV.

Where to Go Next#

  • Functional API: every generator, what its parameters mean, and checks of its output.

  • Composable API: combining inputs with operators and transformations.

  • Custom inputs and pipelines: writing your own Input subclass and building reusable protocols.

Summary#

  • Generators read dt from brainstate.environ; an input of duration \(T\) has \(\lceil T/dt \rceil\) samples.

  • Functional generators return arrays; composable classes return Input objects that produce the same arrays when called.

  • step takes start times. Amplitudes may carry units, which propagate and are checked.

  • Inputs plug into a simulation loop by indexing one sample per step.