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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brainx-skill",
3
- "version": "1.0.11",
3
+ "version": "1.0.12",
4
4
  "description": "Portable BrainX Agent Skills for Claude Code, Codex, Cursor, Windsurf, Gemini CLI, Antigravity, and OpenCode",
5
5
  "license": "Apache-2.0",
6
6
  "type": "commonjs",
@@ -100,7 +100,7 @@ assert voltages.shape[:1] == times.shape
100
100
  assert spikes.shape[:1] == times.shape
101
101
  ```
102
102
 
103
- Treat `V_th` only as the spike-event threshold; it does not change the membrane equation. Keep membrane capacitance and channel conductance density-based in the canonical path. `update()` accepts current density or total current and uses `SingleCompartment.area` to normalize total input; do not manually area-scale only part of the model. Use `size=N` for `N` independent cells, never for `N` compartments.
103
+ Treat `V_th` only as the spike-event threshold; it does not change the membrane equation. Keep membrane capacitance and channel conductance density-based in the canonical path. `update()` accepts current density or total current and uses `SingleCompartment.area` to normalize total input; do not manually area-scale only part of the model. Use `size=N` for `N` independent cells, never for `N` compartments. For a multidimensional condition sweep, use the condition-grid shape as `size` and pass shape-aligned channel parameters and inputs; do not wrap identity functions in `vmap` merely to construct that grid.
104
104
 
105
105
  Open `references/area-scaled-hh-pattern.md` when changing cell geometry or explicitly converting density parameters to total quantities. Open `references/ion-library.md`, `references/channel-library.md`, or `references/mixions-for-adaptation.md` only when the classical fixed-ion HH path is insufficient.
106
106
 
@@ -180,17 +180,3 @@ Open only the smallest reference that owns the non-canonical decision.
180
180
  | `references/mixions-for-adaptation.md` | Adding calcium-dependent adaptation, AHP/KCa currents, rebound, dynamic calcium, or multi-ion channel dependencies. |
181
181
  | `references/multicompartment/multicompartment-cell-workflow.md` | Extending the canonical `Morphology -> Cell -> paint/place -> run` path and selecting the exclusive multicompartment references. |
182
182
  | `references/solver-library-with-effects.md` | Comparing registered integrators, stability, accuracy, and solver-dependent trace effects. |
183
-
184
- ## Application script examples
185
-
186
- Open one script only when its pattern matches the task; each is a complete, runnable program mirrored from the official BrainCell examples.
187
-
188
- | Script | Open when |
189
- |---|---|
190
- | `references/scripts/hh_neuron_basics.py` | Building one end-to-end `SingleCompartment` current-clamp simulation with Na/K/leak currents; this is the default full-script reference. |
191
- | `references/scripts/fi_curve.py` | Producing FI curves, current sweeps, spike counts, or firing rates, where `size=N` means N independent point neurons. |
192
- | `references/scripts/channel_ablation.py` | Comparing intact against ablated dynamics by setting a conductance such as `g_max` to zero while preserving the ion and channel structure. |
193
- | `references/scripts/calcium_channel_gating.py` | Inspecting voltage-dependent activation or inactivation curves through direct channel methods rather than simulating a membrane trace. |
194
- | `references/scripts/spike_frequency_adaptation.py` | Adding spike-frequency adaptation or calcium-dependent afterhyperpolarization with dynamic calcium and `MixIons`. |
195
- | `references/scripts/t_current_rebound.py` | Producing post-inhibitory rebound bursting from a hyperpolarizing step with T-type calcium and HCN currents. |
196
- | `references/scripts/thalamic_neurons.py` | Comparing several thalamic point-neuron phenotypes built from different ion and channel compositions in one script. |
@@ -17,7 +17,12 @@ import brainunit as u
17
17
 
18
18
 
19
19
  class AdaptingCell(braincell.SingleCompartment):
20
- def __init__(self, size, solver="ind_exp_euler"):
20
+ def __init__(
21
+ self,
22
+ size,
23
+ g_ahp=0.3 * u.mS / u.cm**2,
24
+ solver="ind_exp_euler",
25
+ ):
21
26
  super().__init__(
22
27
  size,
23
28
  V_initializer=braintools.init.Constant(-65. * u.mV),
@@ -51,7 +56,7 @@ class AdaptingCell(braincell.SingleCompartment):
51
56
  self.ca.add(ICaHT=braincell.channel.CaHT_HM1992(size, g_max=3.0 * (u.mS / u.cm ** 2)))
52
57
 
53
58
  self.kca = braincell.MixIons(self.k, self.ca)
54
- self.kca.add(IAHP=braincell.channel.AHP_De1994(size, g_max=0.3 * (u.mS / u.cm ** 2)))
59
+ self.kca.add(IAHP=braincell.channel.AHP_De1994(size, g_max=g_ahp))
55
60
 
56
61
  self.IL = braincell.channel.IL(
57
62
  size,
@@ -60,7 +65,25 @@ class AdaptingCell(braincell.SingleCompartment):
60
65
  )
61
66
  ```
62
67
 
63
- ## Rebound Input Variant
68
+ ## Test adaptation by controlled ablation
69
+
70
+ Expose only AHP `g_max`, set it to zero for the ablated condition, and keep the cell template, initialization, solver, stimulus, and every other conductance identical. Use `SingleCompartment.size` for independent conditions; it already owns the batch axis.
71
+
72
+ ```python
73
+ g_ahp = u.math.asarray([0.0, 0.3]) * u.mS / u.cm**2
74
+ cell = AdaptingCell(size=g_ahp.shape, g_ahp=g_ahp)
75
+ current = u.math.asarray([2.0, 2.0]) * u.uA / u.cm**2
76
+ ```
77
+
78
+ Treat the ISI trajectory as the primary adaptation check: the present-AHP lane should lengthen materially while the zero-AHP lane remains more tonic or fires faster late in the stimulus. Report the early/late windows beside rate summaries. Call a condition "intact" only when its complete model and parameter values come from a sourced template; otherwise call it "AHP present" and disclose any calibration.
79
+
80
+ Verify that stimulus onset starts from the intended baseline. If a calibrated hybrid spikes without applied current, use the same disclosed holding current and initialization in every lane, and assert that no spikes occur before the stimulus. Do not interpret an already-spiking baseline as onset adaptation.
81
+
82
+ Do not combine channel families or tune calcium influx, calcium removal, and AHP conductance solely to force the requested contrast. Preserve a coherent template when making biological claims, or label a hybrid explicitly as a teaching model and check that the conclusion survives a small parameter sweep.
83
+
84
+ Open `references/scripts/spike_frequency_adaptation.py` for a runnable calibrated teaching model with a quiet baseline, strength sweep, and zero-conductance comparison. Open `references/scripts/channel_ablation.py` only when the task needs the general one-parameter channel-ablation pattern without calcium-dependent adaptation.
85
+
86
+ ## Rebound input variant
64
87
 
65
88
  For post-inhibitory rebound, add or retain a low-threshold T-type calcium current such as `CaT_HM1992` and drive a time-dependent hyperpolarizing input.
66
89
 
@@ -1,75 +1,135 @@
1
- """
2
- Reference script mirrored from:
3
- https://brainx.chaobrain.com/braincell/examples/spike_frequency_adaptation.html
1
+ """Controlled AHP ablation in a calibrated BrainCell teaching model.
4
2
 
5
- Purpose:
6
- Advanced single-cell mechanism script. Use when the task asks for spike-frequency adaptation, calcium-dependent afterhyperpolarization, dynamic calcium, `MixIons(k, ca)`, or AHP/KCa currents.
3
+ Mechanism pattern:
4
+ https://brainx.chaobrain.com/braincell/examples/spike_frequency_adaptation.html
7
5
 
8
- Use this when:
9
- - The task asks for adaptation or calcium-dependent afterhyperpolarization in a point neuron.
10
- - The agent needs dynamic calcium plus `MixIons(self.k, self.ca)` for AHP/KCa currents.
6
+ Ablation pattern:
7
+ https://brainx.chaobrain.com/braincell/examples/channel_ablation.html
11
8
 
12
- Do not use this when:
13
- - The task only needs the minimal HH Na/K/leak current-clamp pattern.
9
+ This is not a reproduction of one literature neuron. It combines classical HH
10
+ spiking with dynamic calcium and AHP_De1994, then sweeps AHP strength so the
11
+ causal effect is visible and sensitivity to the calibrated value is explicit.
14
12
  """
15
13
 
14
+ import braincell
16
15
  import brainstate
17
16
  import braintools
18
17
  import brainunit as u
19
- import numpy as np
20
18
  import matplotlib.pyplot as plt
21
- import braincell
19
+ import numpy as np
22
20
 
23
21
 
24
22
  class AdaptingCell(braincell.SingleCompartment):
25
- """A thalamic-relay-style cell with Ca-activated K (AHP) current."""
26
- def __init__(self, size, solver='ind_exp_euler'):
27
- super().__init__(size, V_initializer=braintools.init.Constant(-65. * u.mV),
28
- V_th=20. * u.mV, solver=solver)
29
- self.na = braincell.ion.SodiumFixed(size, E=50. * u.mV)
30
- self.na.add(INa=braincell.channel.Na_Ba2002(size, V_sh=-30 * u.mV))
31
- self.k = braincell.ion.PotassiumFixed(size, E=-90. * u.mV)
32
- self.k.add(IKL=braincell.channel.K_Leak(size, g_max=0.01 * (u.mS / u.cm ** 2)))
33
- self.k.add(IDR=braincell.channel.KDR_Ba2002(size, V_sh=-30. * u.mV, q10=2.0, temp=u.celsius2kelvin(16.)))
34
- # Dynamic calcium is an ODE state used by calcium channels and AHP coupling.
35
- self.ca = braincell.ion.CalciumDetailed(size, C_rest=5e-5 * u.mM,
36
- tau=10. * u.ms, d=0.5 * u.um)
37
- self.ca.add(ICaL=braincell.channel.CaL_IS2008(size, g_max=0.5 * (u.mS / u.cm ** 2)))
38
- self.ca.add(ICaN=braincell.channel.CaN_IS2008(size, g_max=0.5 * (u.mS / u.cm ** 2)))
39
- self.ca.add(ICaT=braincell.channel.CaT_HM1992(size, g_max=2.1 * (u.mS / u.cm ** 2)))
40
- self.ca.add(ICaHT=braincell.channel.CaHT_HM1992(size, g_max=3.0 * (u.mS / u.cm ** 2)))
41
- # AHP current depends on both potassium reversal and calcium concentration.
23
+ """Single-compartment teaching model with removable Ca-activated K current."""
24
+
25
+ def __init__(self, size, g_ahp, solver="exp_euler"):
26
+ super().__init__(
27
+ size,
28
+ C=1.0 * u.uF / u.cm**2,
29
+ V_initializer=braintools.init.Constant(-75.0 * u.mV),
30
+ V_th=20.0 * u.mV,
31
+ solver=solver,
32
+ )
33
+ self.na = braincell.ion.SodiumFixed(size, E=50.0 * u.mV)
34
+ self.na.add(INa=braincell.channel.Na_HH1952(size))
35
+
36
+ self.k = braincell.ion.PotassiumFixed(size, E=-77.0 * u.mV)
37
+ self.k.add(IK=braincell.channel.K_HH1952(size))
38
+
39
+ # These teaching values are calibrated, not a sourced cell phenotype.
40
+ self.ca = braincell.ion.CalciumDetailed(
41
+ size,
42
+ C_rest=5.0e-5 * u.mM,
43
+ tau=80.0 * u.ms,
44
+ d=0.5 * u.um,
45
+ )
46
+ self.ca.add(
47
+ ICaL=braincell.channel.CaL_IS2008(
48
+ size,
49
+ g_max=5.0 * u.mS / u.cm**2,
50
+ )
51
+ )
52
+
42
53
  self.kca = braincell.MixIons(self.k, self.ca)
43
- self.kca.add(IAHP=braincell.channel.AHP_De1994(size, g_max=0.3 * (u.mS / u.cm ** 2)))
44
- self.IL = braincell.channel.IL(size, g_max=0.0075 * (u.mS / u.cm ** 2), E=-70 * u.mV)
54
+ self.kca.add(
55
+ IAHP=braincell.channel.AHP_De1994(size, g_max=g_ahp)
56
+ )
57
+ self.IL = braincell.channel.IL(
58
+ size,
59
+ E=-54.387 * u.mV,
60
+ g_max=0.03 * u.mS / u.cm**2,
61
+ )
62
+
45
63
 
64
+ dt = 0.01 * u.ms
65
+ stimulus_on = 50.0 * u.ms
66
+ stimulus_off = 550.0 * u.ms
67
+ holding_current = -0.5 * u.uA / u.cm**2
68
+ g_ahp = u.math.asarray([0.0, 0.3, 1.0]) * u.mS / u.cm**2
69
+ current = u.math.asarray([10.0, 10.0, 10.0]) * u.uA / u.cm**2
46
70
 
47
- cell = AdaptingCell(1)
48
- cell.init_state()
71
+ cell = AdaptingCell(size=g_ahp.shape, g_ahp=g_ahp)
49
72
 
50
- I = 2. * u.uA / u.cm ** 2
73
+ with brainstate.environ.context(dt=dt):
74
+ cell.init_state()
75
+ times = u.math.arange(0.0 * u.ms, 600.0 * u.ms, dt)
51
76
 
77
+ def step(t):
78
+ injected = u.math.where(
79
+ (t >= stimulus_on) & (t < stimulus_off),
80
+ current,
81
+ holding_current,
82
+ )
83
+ with brainstate.environ.context(t=t):
84
+ spike = cell.update(injected)
85
+ return cell.V.value, spike
52
86
 
53
- def step(t):
54
- with brainstate.environ.context(t=t):
55
- cell.update(I)
56
- return cell.V.value, cell.spike.value
87
+ voltages, spikes = brainstate.transform.for_loop(step, times)
57
88
 
89
+ times_ms = np.asarray(times.to_decimal(u.ms))
90
+ pre_stimulus_spikes = np.asarray(spikes[times < stimulus_on]).sum()
91
+ assert pre_stimulus_spikes == 0
58
92
 
59
- with brainstate.environ.context(dt=0.01 * u.ms):
60
- times = u.math.arange(0. * u.ms, 500. * u.ms, brainstate.environ.get_dt())
61
- vs, spikes = brainstate.transform.for_loop(step, times)
93
+ isis = []
94
+ for i, strength in enumerate(g_ahp.to_decimal(u.mS / u.cm**2)):
95
+ spike_times = times_ms[np.asarray(spikes[:, i]) > 0]
96
+ spike_times = spike_times[
97
+ (spike_times >= stimulus_on.to_decimal(u.ms))
98
+ & (spike_times < stimulus_off.to_decimal(u.ms))
99
+ ]
100
+ isi = np.diff(spike_times)
101
+ isis.append(isi)
102
+ print(
103
+ f"g_AHP={strength:.1f} mS/cm^2: {spike_times.size} spikes, "
104
+ f"first ISI={isi[0]:.2f} ms, last ISI={isi[-1]:.2f} ms"
105
+ )
62
106
 
63
- spike_times = np.asarray(times[u.math.squeeze(spikes) > 0] / u.ms)
64
- isi = np.diff(spike_times)
65
- print('number of spikes:', spike_times.size)
66
- print('first ISIs (ms):', np.round(isi[:6], 2).tolist())
107
+ # The ablated lane is tonic; the calibrated present-AHP lane adapts strongly.
108
+ assert abs(isis[0][-1] - isis[0][0]) / isis[0][0] < 0.10
109
+ assert isis[-1][-1] / isis[-1][0] > 1.50
67
110
 
68
- fig, axs = plt.subplots(2, 1, figsize=(8, 5))
69
- axs[0].plot(times / u.ms, u.math.squeeze(vs) / u.mV, linewidth=0.8)
70
- axs[0].set_xlabel('Time (ms)'); axs[0].set_ylabel('V (mV)')
71
- axs[0].set_title('Membrane potential under sustained drive')
72
- axs[1].plot(np.arange(1, isi.size + 1), isi, 'o-')
73
- axs[1].set_xlabel('Inter-spike interval index'); axs[1].set_ylabel('ISI (ms)')
74
- axs[1].set_title('ISIs lengthen over time (adaptation)')
75
- plt.tight_layout(); plt.show()
111
+ fig, axes = plt.subplots(2, 1, figsize=(8, 5))
112
+ for i, label in ((0, "AHP removed"), (-1, "AHP present (teaching value)")):
113
+ axes[0].plot(
114
+ times_ms,
115
+ np.asarray(voltages[:, i].to_decimal(u.mV)),
116
+ linewidth=0.8,
117
+ label=label,
118
+ )
119
+ axes[1].plot(
120
+ np.arange(1, isis[i].size + 1),
121
+ isis[i],
122
+ "o-",
123
+ markersize=3,
124
+ label=label,
125
+ )
126
+ axes[0].set(
127
+ xlabel="Time (ms)",
128
+ ylabel="V (mV)",
129
+ title="Matched steady-current conditions from a quiet baseline",
130
+ )
131
+ axes[1].set(xlabel="ISI index", ylabel="ISI (ms)", title="AHP-dependent slowing")
132
+ for axis in axes:
133
+ axis.legend(frameon=False)
134
+ plt.tight_layout()
135
+ plt.show()
@@ -261,7 +261,6 @@ Verify `postsynaptic_input.shape == connectivity.shape[1:]` for vector input and
261
261
  | `references/custom-operators-gpu.md` | Open when a custom operation targets GPU; it contains Numba CUDA, Warp, raw CUDA, GPU and multi-backend registration, stream and ABI rules, compiler controls, caching, diagnostics, and verification workflows. |
262
262
 
263
263
  ## Application script examples
264
-
265
264
  | Reference | Open when |
266
265
  |---|---|
267
266
  | `references/scripts/coba_ei_teaching.py` | Open for the shared BrainEvent and BrainPy teaching example; it uses `BinaryArray` with interchangeable `FixedNumPerPre`, `CSR`, and dense connectivity for efficient event-driven communication into BrainPy `LIFRef`, `Expon`, and `COBA` dynamics inside one compiled BrainState loop. |
@@ -2,273 +2,106 @@
2
2
 
3
3
  Use this reference when binary pre- or postsynaptic events must modify stored synaptic weights. Plasticity is an overlay on the core `BinaryArray @ connectivity` workflow, not a prerequisite for ordinary event-driven communication.
4
4
 
5
- BrainEvent's event-driven plasticity operators touch only weights connected to neurons that fired, following the same event-sparsity principle as its matrix products.
5
+ BrainEvent's event-driven plasticity operators touch only weights connected to neurons that fired. Keep persistent weights and temporal traces in BrainState State so the complete online update can run inside State-aware transforms.
6
6
 
7
7
  ## Choose the update operator
8
8
 
9
9
  | Weight storage | Presynaptic event triggers update | Postsynaptic event triggers update | Use when |
10
10
  |---|---|---|---|
11
- | CSR | `update_csr_on_binary_pre()` | `update_csr_on_binary_post()` | Connectivity is sparse and fixed; only stored synapses should be visited |
12
- | Dense | `update_dense_on_binary_pre()` | `update_dense_on_binary_post()` | A small fully connected layer already uses a dense weight matrix |
11
+ | CSR | `update_csr_on_binary_pre()` | `update_csr_on_binary_post()` | Connectivity is sparse and fixed; only stored synapses should be visited. |
12
+ | Dense | `update_dense_on_binary_pre()` | `update_dense_on_binary_post()` | A small fully connected layer already uses a dense weight matrix. |
13
13
 
14
- Use the `*_on_binary_pre` direction when the source neuron firing triggers the rule. Use the `*_on_binary_post` direction when the target neuron firing triggers it.
14
+ Use the `*_on_binary_pre` direction when the source neuron firing triggers the rule. Use the `*_on_binary_post` direction when the target neuron firing triggers it. For a bidirectional STDP rule, apply both directions with the traces and signs defined by that rule; do not substitute one trigger direction for the other.
15
15
 
16
- ## Canonical CSR STDP overlay
16
+ ## Run online plasticity through State
17
17
 
18
- The official tutorial maintains exponentially decaying pre/post traces, applies a spike-triggered update to the CSR `data`, and rebuilds the CSR object while preserving its structural arrays.
18
+ Each timestep reads event arrays, advances trace State, and writes persistent weight State; lower that complete ordered update through `for_loop` and compile it with BrainState `jit`.
19
19
 
20
- ```python
21
- import brainevent
22
- import brainstate
23
- import jax.numpy as jnp
24
- import numpy as np
25
-
26
- n_pre = 100
27
- n_post = 50
28
- connection_probability = 0.1
29
-
30
- # Create explicit sparse weights and convert their COO indices to CSR.
31
- brainstate.random.seed(42)
32
- mask = brainstate.random.bernoulli(
33
- connection_probability,
34
- size=(n_pre, n_post),
35
- )
36
- weights_dense = (
37
- brainstate.random.uniform(0.0, 0.5, size=(n_pre, n_post))
38
- * mask
39
- )
40
- row, col = jnp.where(weights_dense != 0)
41
- data = weights_dense[row, col]
42
- indptr, indices, order = brainevent.coo2csr(
43
- row,
44
- col,
45
- shape=(n_pre, n_post),
46
- )
47
- csr_weights = brainevent.CSR(
48
- (data[order], indices, indptr),
49
- shape=(n_pre, n_post),
50
- )
51
-
52
- # Initialize traces and the official presynaptic-triggered STDP parameters.
53
- pre_trace = jnp.zeros(n_pre)
54
- post_trace = jnp.zeros(n_post)
55
- decay_pre = np.exp(-1.0 / 20.0)
56
- decay_post = np.exp(-1.0 / 20.0)
57
- A_plus = 0.005
58
- initial_mean = csr_weights.data.mean()
59
-
60
- brainstate.random.seed(100)
61
- for _ in range(500):
62
- pre_spike = brainstate.random.bernoulli(0.05, size=(n_pre,))
63
- post_spike = brainstate.random.bernoulli(0.05, size=(n_post,))
64
-
65
- pre_trace = (
66
- pre_trace * decay_pre
67
- + pre_spike.astype(jnp.float32)
68
- )
69
- post_trace = (
70
- post_trace * decay_post
71
- + post_spike.astype(jnp.float32)
72
- )
73
-
74
- new_data = brainevent.update_csr_on_binary_pre(
75
- weight=csr_weights.data,
76
- indices=csr_weights.indices,
77
- indptr=csr_weights.indptr,
78
- pre_spike=pre_spike,
79
- post_trace=post_trace * A_plus,
80
- w_min=0.0,
81
- w_max=1.0,
82
- shape=csr_weights.shape,
83
- )
84
- csr_weights = brainevent.CSR(
85
- (new_data, csr_weights.indices, csr_weights.indptr),
86
- shape=csr_weights.shape,
87
- )
88
-
89
- print("connections:", csr_weights.nse)
90
- print("initial mean weight:", initial_mean)
91
- print("final mean weight:", csr_weights.data.mean())
92
- print(
93
- "final range:",
94
- csr_weights.data.min(),
95
- csr_weights.data.max(),
96
- )
97
- ```
98
-
99
- This mirrors the official sparse-network construction and learning loop while using only the presynaptic CSR update API. Preserve `indices`, `indptr`, and `shape`; the operator updates weight values, not the sparse topology.
100
-
101
- For a bidirectional STDP rule, combine the corresponding pre- and post-triggered operators with the appropriate traces and signs from the learning rule. Do not silently substitute the pre-triggered operator for a post-triggered update.
102
-
103
- ## Application: adaptive two-layer spiking network
104
-
105
- The official self-learning practice stores two CSR layers, propagates binary events through both, maintains decaying traces, and applies presynaptic-triggered updates after each sample.
20
+ | API | Description |
21
+ |---|---|
22
+ | `brainstate.LongTermState(weight)` | Use for learned weights that must persist across trial resets and later rollouts; assign the update result through `.value`. |
23
+ | `brainstate.ShortTermState(trace)` | Use for decaying pre- or postsynaptic traces that belong to one sequence; reset them at every independent sequence boundary. |
24
+ | `update_csr_on_binary_pre(...)` | Use when active presynaptic rows update stored CSR data from a postsynaptic trace; it returns new data with the same shape and optionally clips it to `w_min` and `w_max`. |
25
+ | `brainstate.transform.for_loop(step, *events)` | Use for the ordered event sequence; it slices the leading time axis and preserves State effects between steps. |
26
+ | `brainstate.transform.jit(run)` | Use around the complete online sequence so State discovery and write-back remain transform-aware. |
106
27
 
107
28
  ```python
108
29
  import brainevent
109
30
  import brainstate
31
+ import brainunit as u
110
32
  import jax.numpy as jnp
111
- import numpy as np
112
-
113
-
114
- def dense_to_csr(weights):
115
- row, col = jnp.where(weights != 0)
116
- data = weights[row, col]
117
- indptr, indices, order = brainevent.coo2csr(
118
- row,
119
- col,
120
- shape=weights.shape,
121
- )
122
- return brainevent.CSR(
123
- (data[order], indices, indptr),
124
- shape=weights.shape,
125
- )
126
-
127
33
 
128
- class AdaptiveSpikingNetwork:
129
- def __init__(
130
- self,
131
- n_input,
132
- n_hidden,
133
- n_output,
134
- connection_probability=0.15,
135
- seed=0,
136
- ):
137
- self.n_input = n_input
138
- self.n_hidden = n_hidden
139
- self.n_output = n_output
140
34
 
141
- brainstate.random.seed(seed)
142
- mask1 = brainstate.random.bernoulli(
143
- connection_probability,
144
- size=(n_input, n_hidden),
35
+ class PlasticCSR(brainstate.nn.Module):
36
+ def __init__(self):
37
+ super().__init__()
38
+ self.shape = (3, 2)
39
+ self.indices = jnp.array([0, 1, 0, 1, 0, 1], dtype=jnp.int32)
40
+ self.indptr = jnp.array([0, 2, 4, 6], dtype=jnp.int32)
41
+ self.weight = brainstate.LongTermState(
42
+ jnp.full(6, 0.2, dtype=jnp.float32)
145
43
  )
146
- weights1 = (
147
- brainstate.random.uniform(
148
- 0.0,
149
- 0.3,
150
- size=(n_input, n_hidden),
151
- )
152
- * mask1
44
+ self.post_trace = brainstate.ShortTermState(
45
+ jnp.zeros(2, dtype=jnp.float32)
153
46
  )
154
- self.w1 = dense_to_csr(weights1)
155
47
 
156
- mask2 = brainstate.random.bernoulli(
157
- connection_probability,
158
- size=(n_hidden, n_output),
48
+ def update(self, pre_spike, post_spike):
49
+ decay = u.math.exp(-brainstate.environ.get_dt() / (20.0 * u.ms))
50
+ self.post_trace.value = (
51
+ self.post_trace.value * decay
52
+ + post_spike.astype(jnp.float32)
159
53
  )
160
- weights2 = (
161
- brainstate.random.uniform(
162
- 0.0,
163
- 0.3,
164
- size=(n_hidden, n_output),
165
- )
166
- * mask2
54
+ self.weight.value = brainevent.update_csr_on_binary_pre(
55
+ weight=self.weight.value,
56
+ indices=self.indices,
57
+ indptr=self.indptr,
58
+ pre_spike=pre_spike,
59
+ post_trace=self.post_trace.value * 0.01,
60
+ w_min=0.0,
61
+ w_max=1.0,
62
+ shape=self.shape,
167
63
  )
168
- self.w2 = dense_to_csr(weights2)
64
+ return self.weight.value
169
65
 
170
- self.input_trace = jnp.zeros(n_input)
171
- self.hidden_trace = jnp.zeros(n_hidden)
172
- self.output_trace = jnp.zeros(n_output)
173
- self.decay = np.exp(-1.0 / 20.0)
174
- self.learning_rate = 0.008
175
-
176
- def forward(self, input_spikes, learning=True):
177
- hidden_input = input_spikes @ self.w1
178
- hidden_spikes = brainevent.BinaryArray(hidden_input > 0.5)
179
- output_input = hidden_spikes @ self.w2
180
- output_spikes = brainevent.BinaryArray(output_input > 0.8)
181
-
182
- input_events = input_spikes.value
183
- hidden_events = hidden_spikes.value
184
- output_events = output_spikes.value
185
- self.input_trace = (
186
- self.input_trace * self.decay
187
- + input_events.astype(jnp.float32)
188
- )
189
- self.hidden_trace = (
190
- self.hidden_trace * self.decay
191
- + hidden_events.astype(jnp.float32)
192
- )
193
- self.output_trace = (
194
- self.output_trace * self.decay
195
- + output_events.astype(jnp.float32)
196
- )
197
66
 
198
- if learning:
199
- new_w1 = brainevent.update_csr_on_binary_pre(
200
- weight=self.w1.data,
201
- indices=self.w1.indices,
202
- indptr=self.w1.indptr,
203
- pre_spike=input_events,
204
- post_trace=self.hidden_trace * self.learning_rate,
205
- w_min=0.0,
206
- w_max=1.0,
207
- shape=self.w1.shape,
208
- )
209
- self.w1 = brainevent.CSR(
210
- (new_w1, self.w1.indices, self.w1.indptr),
211
- shape=self.w1.shape,
212
- )
67
+ pre_events = jnp.array(
68
+ [[False, False, False], [True, False, False], [False, True, False]]
69
+ )
70
+ post_events = jnp.array(
71
+ [[True, False], [False, False], [False, True]]
72
+ )
213
73
 
214
- new_w2 = brainevent.update_csr_on_binary_pre(
215
- weight=self.w2.data,
216
- indices=self.w2.indices,
217
- indptr=self.w2.indptr,
218
- pre_spike=hidden_events,
219
- post_trace=self.output_trace * self.learning_rate,
220
- w_min=0.0,
221
- w_max=1.0,
222
- shape=self.w2.shape,
223
- )
224
- self.w2 = brainevent.CSR(
225
- (new_w2, self.w2.indices, self.w2.indptr),
226
- shape=self.w2.shape,
227
- )
74
+ with brainstate.environ.context(dt=1.0 * u.ms):
75
+ rule = PlasticCSR()
228
76
 
229
- return output_input, hidden_spikes, output_spikes
77
+ @brainstate.transform.jit
78
+ def learn():
79
+ return brainstate.transform.for_loop(
80
+ rule.update,
81
+ pre_events,
82
+ post_events,
83
+ )
230
84
 
85
+ weight_history = learn()
231
86
 
232
- network = AdaptiveSpikingNetwork(
233
- n_input=200,
234
- n_hidden=100,
235
- n_output=10,
236
- connection_probability=0.12,
237
- seed=2024,
87
+ learned = brainevent.CSR(
88
+ (rule.weight.value, rule.indices, rule.indptr),
89
+ shape=rule.shape,
238
90
  )
239
- initial_w1 = network.w1.data.mean()
240
- initial_w2 = network.w2.data.mean()
241
- activity = []
91
+ drive = brainevent.BinaryArray(jnp.array([True, False, False])) @ learned
242
92
 
243
- brainstate.random.seed(0)
244
- for _ in range(50):
245
- epoch_output_count = 0
246
- for _ in range(20):
247
- input_spikes = brainevent.BinaryArray(
248
- brainstate.random.bernoulli(0.1, size=(200,))
249
- )
250
- output, _, output_spikes = network.forward(
251
- input_spikes,
252
- learning=True,
253
- )
254
- epoch_output_count += int(jnp.sum(output_spikes.value))
255
- activity.append(epoch_output_count / 20)
256
-
257
- assert output.shape == (10,)
258
- assert network.w1.data.mean() >= initial_w1
259
- assert network.w2.data.mean() >= initial_w2
260
- print("W1 mean:", initial_w1, "->", network.w1.data.mean())
261
- print("W2 mean:", initial_w2, "->", network.w2.data.mean())
262
- print("final output activity:", activity[-1])
93
+ assert weight_history.shape == (3, 6)
94
+ assert drive.shape == (2,)
263
95
  ```
264
96
 
265
- This adapts “Practice: Building a Self-Learning Neural Network,” replaces manual CSR row assembly with `coo2csr()`, and removes visualization-only history. It demonstrates the tutorial’s potentiation path; add the post-triggered operator when the learning rule also requires depression.
97
+ Preserve `indices`, `indptr`, and `shape`; the operator updates stored weight values, not sparse topology. When trials are independent except for learned weights, keep `weight` sequential but reset `post_trace`, neural State, delays, and other per-trial State at every trial boundary; a silent interval is not a reset. If mapped lanes learn independently, give each lane separate weight and trace State. Do not `vmap` sequential trials when trial N+1 must consume weights learned in trial N.
266
98
 
267
99
  ## Storage boundary
268
100
 
269
101
  - Prefer CSR plasticity for large sparse networks with fixed connectivity.
270
102
  - Prefer dense plasticity for small fully connected layers already represented densely.
271
103
  - Do not choose JITC when individual connection weights must be persistently updated; use stored CSR or dense weights.
104
+ - Keep dimensionless efficacy weights dimensionless until a named synaptic or current boundary scales them into a physical quantity.
272
105
 
273
106
  ## Exact API routing
274
107
 
@@ -279,6 +112,17 @@ Open the Matrix Operations API for exact signatures and associated primitives:
279
112
 
280
113
  API: https://brainx.chaobrain.com/brainevent/reference/apis/operations.html
281
114
 
115
+ Open the official Synaptic Plasticity tutorial when choosing trace equations, update signs, or a bidirectional learning rule. The BrainEvent operator applies the supplied update; it does not choose the scientific learning rule.
116
+
117
+ ## Common failures
118
+
119
+ - Storing learned weights or traces in ordinary attributes while a transformed timestep mutates them.
120
+ - Running timesteps in a Python loop instead of one State-aware transformed sequence.
121
+ - Resetting persistent learned weights together with per-sequence traces.
122
+ - Updating CSR data while changing or discarding `indices`, `indptr`, or `shape`.
123
+ - Using a presynaptic-triggered operator for a postsynaptic-triggered term.
124
+ - Interpreting a potentiation-only example as a complete STDP rule.
125
+
282
126
  ## Sources
283
127
 
284
128
  - Tutorial 5: Synaptic Plasticity Modeling - Foundation of Learning and Memory: https://brainx.chaobrain.com/brainevent/tutorials/data-structures/05_synaptic_plasticity.html