brainx-skill 1.0.11 → 1.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/package.json +1 -1
  2. package/skills/braincell/SKILL.md +1 -15
  3. package/skills/braincell/references/mixions-for-adaptation.md +26 -3
  4. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +113 -53
  5. package/skills/brainevent/SKILL.md +0 -1
  6. package/skills/brainevent/references/synaptic-plasticity.md +74 -230
  7. package/skills/brainmass/SKILL.md +10 -5
  8. package/skills/brainmass/references/batch-transform-acceleration.md +44 -3
  9. package/skills/brainmass/references/modellibrary.md +11 -0
  10. package/skills/brainmass/references/simulator-input-monitor-api.md +98 -0
  11. package/skills/brainpy-state/SKILL.md +14 -6
  12. package/skills/brainpy-state/references/array-creation.md +2 -2
  13. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +52 -1
  14. package/skills/brainpy-state/references/braintools/connectivity.md +206 -0
  15. package/skills/brainpy-state/references/braintools/input-current.md +199 -0
  16. package/skills/brainpy-state/references/component-selection.md +20 -5
  17. package/skills/brainpy-state/references/projection-patterns.md +2 -0
  18. package/skills/brainpy-state/references/scripts/sound_localization.py +240 -0
  19. package/skills/brainstate/SKILL.md +11 -15
  20. package/skills/brainstate/agents/openai.yaml +4 -0
  21. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +8 -0
  22. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +1 -1
  23. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +57 -7
  24. package/skills/brainstate/references/collective_model_operations.md +26 -27
  25. package/skills/brainx-general-guard/SKILL.md +62 -37
  26. package/skills/brainx-install/SKILL.md +21 -24
  27. package/skills/brainstate/references/braintools/optimizer.md +0 -179
@@ -0,0 +1,199 @@
1
+ # Braintools input currents
2
+
3
+ Use this reference to generate unit-aware stimulation currents, waveforms,
4
+ pulses, and stochastic processes. Prefer the composable class API when a
5
+ protocol combines, transforms, repeats, or sequences several signals; use the
6
+ functional API for one direct array.
7
+
8
+ ## Choose an interface
9
+
10
+ | Interface | Use when | Result |
11
+ |---|---|---|
12
+ | Composable classes | The protocol needs algebra, clipping, smoothing, time shifts, repetition, overlays, or concatenation | Returns an `Input` object; call it to generate the array. |
13
+ | Functional helpers | One signal can be generated in a single call | Returns the generated array immediately. |
14
+
15
+ Names ending in `Input` or `_input` are deprecated aliases. Use the class and
16
+ function names documented below.
17
+
18
+ ## Time-step and composition model
19
+
20
+ An `Input` stores a duration and reads its time step from
21
+ `brainstate.environ`. Calling it generates a cached array; pass
22
+ `recompute=True` when the stochastic or environmental inputs must be evaluated
23
+ again.
24
+
25
+ | API | Description |
26
+ |---|---|
27
+ | `Input(duration)` | Base class for composable currents. It exposes `duration`, `dt`, `n_steps`, and `shape`. |
28
+ | `input_obj(recompute=False)` | Generate and return the current array. |
29
+ | `input_obj.scale(factor)` | Multiply all values by a factor. |
30
+ | `input_obj.shift(time_shift)` | Delay or advance the signal in time. |
31
+ | `input_obj.clip(min_val, max_val)` | Bound the signal values. |
32
+ | `input_obj.smooth(tau)` | Apply exponential smoothing. |
33
+ | `input_obj.repeat(n_times)` | Repeat the pattern. |
34
+ | `input_obj.apply(func)` | Apply a custom transformation to the generated values. |
35
+ | `a + b`, `a - b`, `a * b`, `a / b`, `-a` | Combine compatible signals pointwise. |
36
+ | `a & b` | Concatenate signals sequentially in time. |
37
+ | `a \| b` | Overlay signals by taking their pointwise maximum. |
38
+
39
+ ```python
40
+ import brainstate
41
+ import brainunit as u
42
+ from braintools.input import Constant, Ramp, Sinusoidal
43
+
44
+ with brainstate.environ.context(dt=0.1 * u.ms):
45
+ baseline = Constant([(0.2 * u.nA, 500 * u.ms)])
46
+ ramp = Ramp(0 * u.nA, 1 * u.nA, 500 * u.ms)
47
+ oscillation = Sinusoidal(
48
+ amplitude=0.5 * u.nA,
49
+ frequency=10 * u.Hz,
50
+ duration=500 * u.ms,
51
+ )
52
+ protocol = (baseline + ramp + 0.5 * oscillation).clip(
53
+ 0 * u.nA,
54
+ 2 * u.nA,
55
+ )
56
+ current = protocol()
57
+ assert current.shape[0] == protocol.n_steps
58
+ ```
59
+
60
+ **Invariant:** set or scope `brainstate.environ.dt` before constructing and
61
+ generating the protocol. A different `dt` changes the number of samples.
62
+
63
+ ## Feed a protocol into a BrainPy-State rollout
64
+
65
+ A generated protocol is time-major data: construct it under the rollout `dt`,
66
+ then give it to `for_loop` so one current sample reaches each model step.
67
+
68
+ | API | Description |
69
+ |---|---|
70
+ | `Constant([(value, duration), ...])` | Use for a baseline-pulse-baseline protocol; calling it under the active `dt` returns one unit-aware sample per step. |
71
+ | `brainstate.transform.for_loop(step, times, current)` | Slice `times` and `current` together along their leading axes and stack the step outputs. |
72
+
73
+ ```python
74
+ import brainpy
75
+ import brainstate
76
+ import braintools
77
+ import brainunit as u
78
+ from braintools.input import Constant
79
+
80
+ with brainstate.environ.context(dt=0.1 * u.ms):
81
+ neuron = brainpy.state.LIFRef(
82
+ 3,
83
+ R=100.0 * u.Mohm,
84
+ tau=20.0 * u.ms,
85
+ V_rest=-65.0 * u.mV,
86
+ V_th=-50.0 * u.mV,
87
+ V_reset=-60.0 * u.mV,
88
+ tau_ref=2.0 * u.ms,
89
+ V_initializer=braintools.init.Constant(-65.0 * u.mV),
90
+ )
91
+ brainstate.nn.init_all_states(neuron)
92
+ protocol = Constant([
93
+ (0.0 * u.nA, 15.0 * u.ms),
94
+ (0.65 * u.nA, 4.0 * u.ms),
95
+ (0.0 * u.nA, 81.0 * u.ms),
96
+ ])
97
+ spark = protocol()
98
+ times = u.math.arange(
99
+ 0.0 * u.ms,
100
+ protocol.duration,
101
+ brainstate.environ.get_dt(),
102
+ )
103
+ edge_mask = u.math.asarray([True, False, False])
104
+
105
+ def step(t, spark_current):
106
+ with brainstate.environ.context(t=t):
107
+ return neuron(0.13 * u.nA + edge_mask * spark_current)
108
+
109
+ spikes = brainstate.transform.for_loop(step, times, spark)
110
+
111
+ assert spikes.shape == (1000, 3)
112
+ ```
113
+
114
+ Do not reconstruct the same sections with comparisons against `t` inside
115
+ `step`. For a mapped parameter sweep that shares this protocol, keep the
116
+ per-step current sample unmapped (`in_axes=None`) while mapping the independent
117
+ condition parameters and dynamical State. Open
118
+ `skills/brainstate/references/brainstate/transformation-vmap-expansion.md` for
119
+ the mapped-State contract.
120
+
121
+ ## Basic currents
122
+
123
+ | Composable API | Functional API | Use |
124
+ |---|---|---|
125
+ | `Section(values, durations)` | `section(values, durations, return_length=False)` | Build consecutive constant sections from parallel value and duration sequences. |
126
+ | `Constant(I_and_duration)` | `constant(I_and_duration)` | Build piecewise-constant sections from `(value, duration)` pairs. |
127
+ | `Step(amplitudes, step_times, duration=None)` | `step(amplitudes, step_times, duration=None)` | Change among discrete levels at specified times. |
128
+ | `Ramp(c_start, c_end, duration, t_start=None, t_end=None)` | `ramp(c_start, c_end, duration, t_start=None, t_end=None)` | Interpolate linearly, optionally only within a subinterval. |
129
+
130
+ `Constant` takes a sequence of pairs:
131
+
132
+ ```python
133
+ from braintools.input import Constant
134
+
135
+ protocol = Constant([
136
+ (0.0 * u.nA, 100 * u.ms),
137
+ (1.0 * u.nA, 200 * u.ms),
138
+ (0.0 * u.nA, 100 * u.ms),
139
+ ])
140
+ ```
141
+
142
+ Use `Section(values=[...], durations=[...])` when separate arrays are more
143
+ convenient.
144
+
145
+ ## Pulse generators
146
+
147
+ | Composable API | Functional API | Use |
148
+ |---|---|---|
149
+ | `Spike(sp_times, duration, sp_lens=..., sp_sizes=...)` | `spike(sp_times, sp_lens, sp_sizes, duration)` | Place short current spikes at explicit times. |
150
+ | `GaussianPulse(amplitude, center, sigma, duration)` | `gaussian_pulse(amplitude, center, sigma, duration, ...)` | Generate a Gaussian-shaped pulse. |
151
+ | `ExponentialDecay(amplitude, tau, duration, ...)` | `exponential_decay(amplitude, tau, duration, ...)` | Generate a one-sided exponential decay. |
152
+ | `DoubleExponential(amplitude, tau_rise, tau_decay, ...)` | `double_exponential(amplitude, tau_rise, tau_decay, ...)` | Generate a rise-and-decay synaptic-current shape. |
153
+ | `Burst(...)` | `burst(...)` | Generate repeated pulses within one or more bursts. |
154
+
155
+ ## Waveforms
156
+
157
+ | Composable API | Functional API | Use |
158
+ |---|---|---|
159
+ | `Sinusoidal(amplitude, frequency, duration, ...)` | `sinusoidal(amplitude, frequency, duration, ...)` | Generate a fixed-frequency sine wave. |
160
+ | `Square(amplitude, frequency, duration, ...)` | `square(amplitude, frequency, duration, ...)` | Generate a square wave; configure its duty cycle deliberately. |
161
+ | `Triangular(amplitude, frequency, duration, ...)` | `triangular(amplitude, frequency, duration, ...)` | Generate a triangular periodic wave. |
162
+ | `Sawtooth(amplitude, frequency, duration, ...)` | `sawtooth(amplitude, frequency, duration, ...)` | Generate a sawtooth periodic wave. |
163
+ | `Chirp(amplitude, f_start, f_end, duration, ...)` | `chirp(amplitude, f_start, f_end, duration, ...)` | Sweep frequency over time. |
164
+ | `NoisySinusoidal(amplitude, frequency, ..., noise_amplitude=...)` | `noisy_sinusoidal(amplitude, frequency, ..., noise_amplitude=...)` | Add stochastic noise to a sinusoid. |
165
+
166
+ ## Stochastic processes
167
+
168
+ | Composable API | Functional API | Use |
169
+ |---|---|---|
170
+ | `WienerProcess(duration, n=1, t_start=None, t_end=None, sigma=1.0, seed=None)` | `wiener_process(duration, sigma=1.0, n=1, ...)` | Model Brownian fluctuations with independent Gaussian increments. |
171
+ | `OUProcess(mean, sigma, tau, duration, n=1, t_start=None, t_end=None, seed=None)` | `ou_process(mean, sigma, tau, duration, n=1, ...)` | Model mean-reverting fluctuations around `mean`. |
172
+ | `Poisson(rate, duration, n=1, t_start=None, t_end=None, amplitude=1.0, seed=None)` | `poisson(rate, duration, amplitude=1.0, n=1, ...)` | Generate independent Poisson spike-current trains. |
173
+
174
+ Use `seed=` for reproducibility and `n=` for multiple independent processes.
175
+ For Poisson input, ensure `rate * dt` is a valid per-bin spike probability.
176
+ Call with `recompute=True` only when a new stochastic realization is intended.
177
+
178
+ ## Composition wrappers
179
+
180
+ These classes are normally created through operators or methods rather than
181
+ instantiated directly.
182
+
183
+ | API | Description |
184
+ |---|---|
185
+ | `Composite(input1, input2, operator)` | Pointwise combination of two inputs. |
186
+ | `ConstantValue(value, duration)` | Promote a scalar to a duration-matched input. |
187
+ | `Sequential(*inputs)` | Time concatenation corresponding to `&`. |
188
+ | `TimeShifted(input_obj, time_shift)` | Result of `.shift()`. |
189
+ | `Clipped(input_obj, min_val=None, max_val=None)` | Result of `.clip()`. |
190
+ | `Smoothed(input_obj, tau)` | Result of `.smooth()`. |
191
+ | `Repeated(input_obj, n_times)` | Result of `.repeat()`. |
192
+ | `Transformed(input_obj, func)` | Result of `.apply()`. |
193
+
194
+ Pointwise operands must have compatible duration, shape, and units. Use `&`
195
+ when durations differ and should occur one after another.
196
+
197
+ ## Official source
198
+
199
+ - `https://brainx.chaobrain.com/braintools/apis/input.html`
@@ -9,11 +9,16 @@ Choose components in dependency order so later decisions preserve earlier semant
9
9
  | Step | Decide | Result |
10
10
  |---|---|---|
11
11
  | 1 | Which firing mechanism must the neuron reproduce? | Neuron family and required numerical resolution |
12
- | 2 | Is the presynaptic source scheduled, stochastic, encoded, or injected directly into State? | Input generator or input function |
13
- | 3 | Which temporal response must a presynaptic event create? | Synaptic dynamics and the valid projection alignment |
14
- | 4 | Should synaptic activity become voltage-dependent conductance or voltage-independent current? | Synaptic output, weight units, signs, and scale |
15
- | 5 | Must efficacy change over recent presynaptic history? | Optional `STP` or `STD` |
16
- | 6 | What tensor and temporal statistic does the loss or analysis consume? | Readout Module or explicit time reduction |
12
+ | 2 | Is the drive a direct current protocol, scheduled or stochastic spike source, encoded value, or direct State injection? | BrainTools current protocol, BrainPy input generator, encoder, or input function |
13
+ | 3 | Which presynaptic/postsynaptic pairs exist, and does geometry or topology determine them? | Connection topology and a `ConnectionResult` when BrainTools owns pair selection |
14
+ | 4 | Which temporal response must a presynaptic event create? | Synaptic dynamics and the valid projection alignment |
15
+ | 5 | Should synaptic activity become voltage-dependent conductance or voltage-independent current? | Synaptic output, weight units, signs, and scale |
16
+ | 6 | Must efficacy change over recent presynaptic history? | Optional `STP` or `STD` |
17
+ | 7 | What tensor and temporal statistic does the loss or analysis consume? | Readout Module or explicit time reduction |
18
+
19
+ Complete steps 3 through 6 whenever a point-neuron task names recurrent excitation, mutual inhibition, or spike-driven connectivity. Use explicit synapses, outputs, communication, and projections; do not substitute a scalar mean-spike feedback `State`. If scalar population rates and rate coupling are the scientific variables, route that scale to BrainMass or open both skills for an explicit hybrid model.
20
+
21
+ When geometry, spatial distance, graph topology, Dale's principle, or compartment targeting determines the edge set, open `references/braintools/connectivity.md` and generate the `ConnectionResult` before selecting CSR, CSC, dense, generated, or fixed-degree BrainEvent storage. Let a projection communication operator own pair selection only when its documented fixed-probability or fixed-degree contract expresses the intended topology directly.
17
22
 
18
23
  After these choices, open `references/projection-patterns.md` to choose AlignPre versus AlignPost, communication, delay integration, and projection construction form.
19
24
 
@@ -110,6 +115,16 @@ Compare firing rate, adaptation, spike onset, and stability at the intended `dt`
110
115
 
111
116
  Choose the source from what is already known and where the generated input should be applied.
112
117
 
118
+ ### Direct current protocols
119
+
120
+ Use a BrainTools current protocol when known time-varying values should enter a neuron's current argument rather than emit spikes or mutate target State.
121
+
122
+ | API family | Use when |
123
+ |---|---|
124
+ | `braintools.input` | Use for unit-aware constant sections, steps, pulses, waveforms, stochastic current processes, and composed protocols; generate a time-major array under the intended `brainstate.environ.dt`. |
125
+
126
+ Open `references/braintools/input-current.md` for API selection, composition, and the BrainPy-State rollout handoff. Generate the complete time-major current once under the rollout `dt`, pass it as an `xs` argument to `for_loop`, and apply spatial masks through unit-aware broadcasting after each sample is sliced. Do not rebuild named sections or pulses from time predicates inside the model step.
127
+
113
128
  ### Scheduled and autonomous spike sources
114
129
 
115
130
  Use this family when the source owns either a prescribed event schedule or a persistent stochastic firing-rate configuration.
@@ -115,6 +115,8 @@ Use `brainstate.nn.EventFixedProb` for the canonical probabilistic sparse-spike
115
115
 
116
116
  Open `references/scripts/103_COBA_2005.py` for a complete E/I COBA projection workflow. Open `references/scripts/109_fast_global_oscillation.py` when the projection uses `DeltaProj` with delayed recurrent input.
117
117
 
118
+ Open `references/scripts/sound_localization.py` when independent conditions require a mapped bank of heterogeneous integer event taps feeding BrainEvent fixed-fan-out communication and coincidence detectors.
119
+
118
120
  ## Official sources
119
121
 
120
122
  - `https://brainx.chaobrain.com/brainpy-state/concepts/model-anatomy.html`
@@ -0,0 +1,240 @@
1
+ """Localize sound direction from interaural spike timing.
2
+
3
+ Positive interaural time difference (ITD) means the right-ear spike arrives
4
+ later, so the source is on the left. Negative ITD means the source is right.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import brainevent
10
+ import brainpy
11
+ import brainstate
12
+ import braintools
13
+ import brainunit as u
14
+ import jax.numpy as jnp
15
+ import numpy as np
16
+ from brainstate.transform import vmap2
17
+ from brainstate.util import filter as util_filter
18
+
19
+
20
+ DT = 0.05 * u.ms
21
+ NUM_STEPS = 80
22
+ DURATION = NUM_STEPS * DT
23
+ SOUND_ONSET = 40 * DT
24
+
25
+ PREFERRED_DELAY_STEPS = jnp.arange(-12, 13, dtype=jnp.int32)
26
+ PREFERRED_ITDS = PREFERRED_DELAY_STEPS * DT
27
+ MAX_INTERNAL_DELAY_STEPS = 12
28
+ EVALUATION_ITDS = u.math.asarray(
29
+ [-0.53, -0.33, -0.17, -0.075, -0.05, 0.0, 0.05, 0.075, 0.17, 0.33, 0.53]
30
+ ) * u.ms
31
+
32
+ V_REST = -60.0 * u.mV
33
+ V_THRESHOLD = -50.0 * u.mV
34
+ V_RESET = -60.0 * u.mV
35
+ AUDITORY_PULSE = 27.0 * u.mA
36
+ DETECTOR_WEIGHT = 24.0 * u.mA
37
+ READOUT_WEIGHT = 120.0 * u.mA
38
+
39
+ DYNAMICAL_STATE = util_filter.Any(
40
+ util_filter.OfType(brainstate.HiddenState),
41
+ util_filter.OfType(brainstate.ShortTermState),
42
+ )
43
+
44
+
45
+ def _lif_population(size: int, tau, tau_ref):
46
+ return brainpy.state.LIFRef(
47
+ size,
48
+ R=1.0 * u.ohm,
49
+ tau=tau,
50
+ tau_ref=tau_ref,
51
+ V_rest=V_REST,
52
+ V_th=V_THRESHOLD,
53
+ V_reset=V_RESET,
54
+ V_initializer=braintools.init.Constant(V_REST),
55
+ )
56
+
57
+
58
+ class EventDelayLine(brainstate.nn.Module):
59
+ """Small integer delay bank with step 0 equal to the current event."""
60
+
61
+ def __init__(self, max_steps: int):
62
+ super().__init__()
63
+ self.max_steps = max_steps
64
+
65
+ def init_state(self):
66
+ self.history = brainstate.HiddenState(
67
+ jnp.zeros((self.max_steps + 1, 2), dtype=jnp.bool_)
68
+ )
69
+
70
+ def update(self, events):
71
+ self.history.value = jnp.concatenate(
72
+ [events[None, :], self.history.value[:-1]],
73
+ axis=0,
74
+ )
75
+ return self.history.value
76
+
77
+
78
+ class SoundLocalizer(brainstate.nn.Module):
79
+ """Two auditory relays, a coincidence bank, and left/right readouts."""
80
+
81
+ def __init__(self):
82
+ super().__init__()
83
+ self.num_detectors = int(PREFERRED_DELAY_STEPS.shape[0])
84
+ self.auditory = _lif_population(2, tau=0.1 * u.ms, tau_ref=0.5 * u.ms)
85
+ self.detectors = _lif_population(
86
+ self.num_detectors,
87
+ tau=0.2 * u.ms,
88
+ tau_ref=0.5 * u.ms,
89
+ )
90
+ self.readout = _lif_population(2, tau=0.5 * u.ms, tau_ref=0.5 * u.ms)
91
+
92
+ self.ear_history = EventDelayLine(MAX_INTERNAL_DELAY_STEPS)
93
+ self.left_delay_steps = jnp.maximum(PREFERRED_DELAY_STEPS, 0)
94
+ self.right_delay_steps = jnp.maximum(-PREFERRED_DELAY_STEPS, 0)
95
+
96
+ detector_targets = jnp.concatenate(
97
+ [jnp.arange(self.num_detectors), jnp.arange(self.num_detectors)]
98
+ )[:, None]
99
+ self.detector_connection = brainevent.FixedNumPerPre(
100
+ DETECTOR_WEIGHT,
101
+ detector_targets,
102
+ shape=(2 * self.num_detectors, self.num_detectors),
103
+ )
104
+
105
+ readout_targets = jnp.where(PREFERRED_DELAY_STEPS > 0, 0, 1)[:, None]
106
+ readout_weights = (
107
+ (PREFERRED_DELAY_STEPS != 0).astype(jnp.float32)[:, None]
108
+ * READOUT_WEIGHT
109
+ )
110
+ self.readout_connection = brainevent.FixedNumPerPre(
111
+ readout_weights,
112
+ readout_targets,
113
+ shape=(self.num_detectors, 2),
114
+ )
115
+
116
+ def update(self, t, itd_step):
117
+ with brainstate.environ.context(t=t):
118
+ arrivals = u.math.asarray(
119
+ [SOUND_ONSET, SOUND_ONSET + itd_step * DT]
120
+ )
121
+ ear_drive = (
122
+ u.math.abs(t - arrivals) < 0.25 * brainstate.environ.get_dt()
123
+ ) * AUDITORY_PULSE
124
+ ear_spikes = self.auditory(ear_drive) != 0.0
125
+
126
+ history = self.ear_history.update(ear_spikes)
127
+ left_events = history[self.left_delay_steps, 0]
128
+ right_events = history[self.right_delay_steps, 1]
129
+ delayed_events = jnp.concatenate([left_events, right_events])
130
+
131
+ detector_current = (
132
+ brainevent.BinaryArray(delayed_events) @ self.detector_connection
133
+ )
134
+ detector_spikes = self.detectors(detector_current) != 0.0
135
+
136
+ readout_current = (
137
+ brainevent.BinaryArray(detector_spikes) @ self.readout_connection
138
+ )
139
+ readout_spikes = self.readout(readout_current) != 0.0
140
+ return ear_spikes, detector_spikes, readout_spikes
141
+
142
+
143
+ def simulate_itds(itds=EVALUATION_ITDS):
144
+ """Round unit-bearing ITDs to ``dt`` and evaluate independent conditions."""
145
+ itds = u.math.asarray(itds, unit=u.ms)
146
+ if itds.ndim != 1:
147
+ raise ValueError("itds must be a one-dimensional time quantity")
148
+ itd_steps = jnp.rint(
149
+ itds.to_decimal(u.ms) / DT.to_decimal(u.ms)
150
+ ).astype(jnp.int32)
151
+
152
+ with brainstate.environ.context(dt=DT):
153
+ net = SoundLocalizer()
154
+ brainstate.nn.vmap_init_all_states(net, axis_size=itds.shape[0])
155
+ mapped_step = vmap2(
156
+ net.update,
157
+ in_axes=(None, 0),
158
+ out_axes=0,
159
+ state_in_axes={0: DYNAMICAL_STATE},
160
+ state_out_axes={0: DYNAMICAL_STATE},
161
+ unexpected_out_state_mapping="raise",
162
+ )
163
+ times = u.math.arange(0.0 * u.ms, DURATION, DT)
164
+
165
+ def step(t):
166
+ return mapped_step(t, itd_steps)
167
+
168
+ ear_spikes, detector_spikes, readout_spikes = (
169
+ brainstate.transform.for_loop(step, times)
170
+ )
171
+
172
+ return (
173
+ jnp.sum(ear_spikes, axis=0),
174
+ jnp.sum(detector_spikes, axis=0),
175
+ jnp.sum(readout_spikes, axis=0),
176
+ )
177
+
178
+
179
+ def decode_directions(detector_counts, readout_counts):
180
+ """Decode only rows supported by coincidence-detector evidence."""
181
+ detectors = np.asarray(detector_counts)
182
+ counts = np.asarray(readout_counts)
183
+ if np.any(detectors.sum(axis=1) == 0):
184
+ raise ValueError("cannot decode a condition with no detector evidence")
185
+
186
+ labels = np.full(counts.shape[0], "CENTER", dtype="<U6")
187
+ labels[counts[:, 0] > counts[:, 1]] = "LEFT"
188
+ labels[counts[:, 1] > counts[:, 0]] = "RIGHT"
189
+
190
+ ties = counts[:, 0] == counts[:, 1]
191
+ winning_steps = np.asarray(PREFERRED_DELAY_STEPS)[np.argmax(detectors, axis=1)]
192
+ if np.any(ties & (winning_steps != 0)):
193
+ raise ValueError("readout tie is not supported by the center detector")
194
+ return labels
195
+
196
+
197
+ def assert_delay_convention():
198
+ """Prove that tap 3 returns an impulse after three completed updates."""
199
+ with brainstate.environ.context(dt=DT):
200
+ delay = EventDelayLine(max_steps=3)
201
+ brainstate.nn.init_all_states(delay)
202
+ impulse = jnp.zeros((5, 2), dtype=jnp.bool_).at[0, 0].set(True)
203
+ history = brainstate.transform.for_loop(delay.update, impulse)
204
+ expected = jnp.array([False, False, False, True, False])
205
+ assert jnp.array_equal(history[:, 3, 0], expected)
206
+
207
+
208
+ def main():
209
+ assert_delay_convention()
210
+ ear_counts, detector_counts, readout_counts = simulate_itds()
211
+ directions = decode_directions(detector_counts, readout_counts)
212
+ evaluated = np.asarray(EVALUATION_ITDS.to_decimal(u.ms))
213
+ preferences = np.asarray(PREFERRED_ITDS.to_decimal(u.ms))
214
+ detectors = np.asarray(detector_counts)
215
+ readouts = np.asarray(readout_counts)
216
+
217
+ print(" ITD (ms) | detector (ms) | L/R spikes | direction")
218
+ print("----------+---------------+------------+----------")
219
+ for itd, detector_row, readout_row, direction in zip(
220
+ evaluated, detectors, readouts, directions
221
+ ):
222
+ detector_itd = preferences[int(np.argmax(detector_row))]
223
+ print(
224
+ f"{itd:9.2f} | {detector_itd:13.2f} |"
225
+ f" {readout_row[0]:3d}/{readout_row[1]:<3d} | {direction}"
226
+ )
227
+
228
+ if not np.all(np.asarray(ear_counts) == 1):
229
+ raise RuntimeError("each auditory relay must emit exactly one spike")
230
+ expected = np.where(
231
+ evaluated < 0.0,
232
+ "RIGHT",
233
+ np.where(evaluated > 0.0, "LEFT", "CENTER"),
234
+ )
235
+ if not np.array_equal(directions, expected):
236
+ raise RuntimeError("direction decoding failed")
237
+
238
+
239
+ if __name__ == "__main__":
240
+ main()
@@ -3,7 +3,7 @@ name: brainstate
3
3
  description: BrainState is the central stateful execution infrastructure for BrainX modeling and simulation. Use this skill for mutable State and `.value`, ParamState and other State roles, Module graphs, environment-scoped simulations, state initialization, operational randomness, size-aware neural-network composition, state-aware jit/grad/vmap, or a BrainState training step.
4
4
  ---
5
5
 
6
- # BrainState
6
+ # Brainstate
7
7
 
8
8
  ## Purpose and boundary
9
9
 
@@ -299,7 +299,7 @@ batched_prediction = predict_batch(x_train)
299
299
  assert batched_prediction.shape == (64, 1)
300
300
  ```
301
301
 
302
- This maps a function written for one example over a batch. Open the `vmap` expansion for mapped State axes, ensembles, parameter sweeps, or the documented `state_in_axes` / `state_out_axes` controls. The routed tutorial does not define the rough draft's `in_states` / `out_states` names.
302
+ This maps a function written for one example over a batch. Open the `vmap` expansion for mapped State axes, ensembles, or parameter sweeps. Use `vmap(..., in_states=..., out_states=...)` to declare specific mapped State instances; use `vmap2(..., state_in_axes=..., state_out_axes=...)` to select State by filters with configurable output-axis inference. Do not add either transform when the owning package already exposes the required batch axis.
303
303
 
304
304
  ### 6. Randomness
305
305
 
@@ -334,6 +334,13 @@ assert input_spikes.shape == (num_steps, batch_size, num_inputs)
334
334
 
335
335
  Open `references/brainstate/randomness-and-reproducibility.md` for independent `RandomState` streams, direct key control, stochastic mapping, exact replay, or checkpointed RNG State.
336
336
 
337
+ ## Script references
338
+
339
+ - `scripts/integrator_rnn.py`: full stateful sequence-training workflow with a custom RNN cell, trainable initial state, optimization, compiled steps, and evaluation.
340
+ - `scripts/lif_neuron_model.py`: extended combination of `HiddenState`, `ShortTermState`, and `ParamState` with explicit `.value` updates.
341
+ - `scripts/modern_cnn.py`: full convolution, normalization, activation, pooling, dropout, and dense Module composition. Select it through the layer or activation branch.
342
+ - `scripts/resnet.py`: residual Modules and dynamically registered child blocks.
343
+
337
344
  ## Reference routing
338
345
 
339
346
  Route by the outcome the task needs, then open only the smallest reference that owns that variant.
@@ -365,12 +372,12 @@ Route by the outcome the task needs, then open only the smallest reference that
365
372
  | Reference | Open when |
366
373
  |---|---|
367
374
  | `references/brainstate/parameter-constraints-regularization.md` | Using `nn.Param` transforms, regularizers, priors, penalties, or `nn.Const` |
368
- | `references/braintools/optimizer.md` | Selecting a `braintools.optim`, Optax, SciPy, or Nevergrad optimizer or scheduler |
375
+ | `references/braintools-optimizer-reference.md` | Selecting a `braintools.optim`, Optax, SciPy, or Nevergrad optimizer or scheduler |
369
376
  | `references/brainstate/randomness-and-reproducibility.md` | Creating independent random streams or exact stochastic replay across transforms and checkpoints |
370
377
 
371
378
  The remaining nested reference has one inbound route:
372
379
 
373
- - Only `references/brainstate/parameter-constraints-regularization.md` may open `references/brainstate/parameter-transforms-regularizers-catalog.md`.
380
+ - Only `parameter-constraints-regularization.md` may open `parameter-transforms-regularizers-catalog.md`.
374
381
 
375
382
  ### Layer libraries
376
383
 
@@ -390,14 +397,3 @@ The remaining nested reference has one inbound route:
390
397
  | `references/brainstate/brainstate-transformed-diagnostics.md` | Debugging runtime values or enforcing invariants inside transformed stateful code |
391
398
 
392
399
  Do not route to dynamics or solver references from this skill; they are outside the architecture supplied for this BrainState skill.
393
-
394
- ## Application script examples
395
-
396
- Open one script only when its pattern matches the task; each is a complete, runnable program.
397
-
398
- | Script | Open when |
399
- |---|---|
400
- | `scripts/integrator_rnn.py` | Building a full stateful sequence-training workflow with a custom RNN cell, trainable initial state, optimization, compiled steps, and evaluation. |
401
- | `scripts/lif_neuron_model.py` | Combining `HiddenState`, `ShortTermState`, and `ParamState` in one Module with explicit `.value` updates. |
402
- | `scripts/modern_cnn.py` | Composing convolution, normalization, activation, pooling, dropout, and dense Modules; select it through the layer or activation branch. |
403
- | `scripts/resnet.py` | Building residual Modules and dynamically registered child blocks. |
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "BrainState"
3
+ short_description: "Build stateful BrainState modules and transforms"
4
+ default_prompt: "Use $brainstate to build or debug a stateful BrainState model."
@@ -205,6 +205,14 @@ gradients through a long rollout make activation memory the binding constraint.
205
205
  Tune `base` by measuring peak memory and step time: it controls checkpoint
206
206
  granularity, so lower memory requires more backward recomputation.
207
207
 
208
+ Choose the transform boundary from the State lifecycle, not from a goal of
209
+ eliminating every host loop. Put all timesteps of one logical rollout in
210
+ `for_loop` or `scan`. When trials must remain sequential because learned State
211
+ passes from trial N to trial N+1, but neural and short-term State must reset at
212
+ each trial boundary, compile one complete trial callable and use a small host
213
+ loop across trials. Do not nest the trials in another transformed loop when
214
+ that prevents the required selective reset.
215
+
208
216
  **Invariant:** Initialize recurrent State before each rollout, keep the
209
217
  checkpointed loop inside `loss_fn`, differentiate that loss, then JIT the whole
210
218
  training step. Checkpointing changes the memory/compute profile, not the
@@ -440,7 +440,7 @@ def train_step(x, y):
440
440
  return loss
441
441
  ```
442
442
 
443
- Return to `skills/brainstate/SKILL.md` for the general training structure. Open `references/braintools/optimizer.md` only for optimizer or scheduler selection.
443
+ Return to `skills/brainstate/SKILL.md` for the general training structure. Open `references/braintools-optimizer-reference.md` only for optimizer or scheduler selection.
444
444
 
445
445
  Official source: https://brainx.chaobrain.com/brainstate/tutorials/core/07_training_and_metrics.html
446
446