brainx-skill 1.0.8 → 1.0.9
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.
- package/README.md +1 -6
- package/manifest.json +3 -2
- package/package.json +2 -1
- package/skills/braincell/SKILL.md +1 -1
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +107 -44
- package/skills/braincell/references/channel-library.md +0 -85
- package/skills/braincell/references/ion-library.md +0 -67
- package/skills/braincell/references/multicompartment/filter-function-library.md +0 -8
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +204 -65
- package/skills/brainmass/SKILL.md +290 -0
- package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
- package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
- package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainmass/references/braintools/cogtask.md +190 -0
- package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
- package/skills/brainmass/references/braintools/metric.md +157 -0
- package/skills/brainmass/references/braintools/optimizer.md +187 -0
- package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
- package/skills/brainmass/references/braintools/surrogate.md +151 -0
- package/skills/brainmass/references/coupling-network-api.md +148 -0
- package/skills/brainmass/references/datasets-api.md +72 -0
- package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
- package/skills/brainmass/references/forward-observation-api.md +131 -0
- package/skills/brainmass/references/horn-task-training.md +199 -0
- package/skills/brainmass/references/modellibrary.md +104 -0
- package/skills/brainmass/references/noiseprocesses.md +121 -0
- package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
- package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
- package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
- package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
- package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
- package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
- package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
- package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
- package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
- package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
- package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
- package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
- package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
- package/skills/brainmass/references/visualization-analysis-api.md +130 -0
- package/skills/brainpy-state/SKILL.md +1 -1
- package/skills/brainx-general-guard/SKILL.md +43 -128
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +0 -303
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +0 -62
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Reference script mirrored from:
|
|
2
|
+
https://brainx.chaobrain.com/brainmass/gallery/model_zoo/wong_wang_exc_inh.html
|
|
3
|
+
|
|
4
|
+
Converted from the official notebook at upstream commit
|
|
5
|
+
293eaeb8948474c645208b68c531b7cb5482d4fb. Notebook outputs are omitted and
|
|
6
|
+
``%matplotlib inline`` remains commented; code and Markdown cells are preserved.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
# %% tags=["remove-cell"]
|
|
10
|
+
# %matplotlib inline
|
|
11
|
+
import brainmass
|
|
12
|
+
import brainstate
|
|
13
|
+
import brainunit as u
|
|
14
|
+
import jax.numpy as jnp
|
|
15
|
+
import numpy as np
|
|
16
|
+
import matplotlib.pyplot as plt
|
|
17
|
+
brainstate.random.seed(0)
|
|
18
|
+
brainstate.environ.set(dt=0.1 * u.ms)
|
|
19
|
+
|
|
20
|
+
# %% [markdown]
|
|
21
|
+
# # Wong-Wang Excitatory-Inhibitory (Dynamic Mean Field)
|
|
22
|
+
#
|
|
23
|
+
# The **two-population (excitatory-inhibitory) reduced Wong-Wang model**, often called the *dynamic mean field* (DMF), is the resting-state workhorse for whole-brain modeling. Each region has an excitatory NMDA gating variable $S_E$ and an inhibitory GABA gating variable $S_I$; a feedback-inhibition weight $J_i$ regulates the local excitation-inhibition balance so that the excitatory population settles near a biologically plausible ~3 Hz resting rate. It is the node model behind much resting-state BOLD / functional-connectivity work.
|
|
24
|
+
#
|
|
25
|
+
# *(Distinct from the reduced two-choice* `WongWangStep` *decision model.)*
|
|
26
|
+
#
|
|
27
|
+
# **Reference:** Deco, Ponce-Alvarez, Hagmann, Romani, Mantini & Corbetta (2014), *How local excitation-inhibition ratio impacts the whole brain dynamics*, Journal of Neuroscience 34(23):7886-7898.
|
|
28
|
+
|
|
29
|
+
# %% [markdown]
|
|
30
|
+
# ## Build the model
|
|
31
|
+
|
|
32
|
+
# %%
|
|
33
|
+
node = brainmass.WongWangExcInhStep(in_size=1, J_i=1.0, G=2.0)
|
|
34
|
+
node
|
|
35
|
+
|
|
36
|
+
# %% [markdown]
|
|
37
|
+
# ## Run a simulation
|
|
38
|
+
#
|
|
39
|
+
# We monitor the excitatory gating variable `S_e` and the derived excitatory firing rate via the `H_e()` observable.
|
|
40
|
+
|
|
41
|
+
# %%
|
|
42
|
+
sim = brainmass.Simulator(node, dt=0.1 * u.ms)
|
|
43
|
+
res = sim.run(3000. * u.ms,
|
|
44
|
+
monitors={'S_e': 'S_e', 'rate_e': lambda m: m.H_e()})
|
|
45
|
+
float(u.get_magnitude(res['rate_e'])[-1, 0]) # resting excitatory rate (Hz)
|
|
46
|
+
|
|
47
|
+
# %% [markdown]
|
|
48
|
+
# ## Visualize
|
|
49
|
+
#
|
|
50
|
+
# The gating variable settles to a steady value and the excitatory rate stabilizes near the ~3 Hz resting fixed point.
|
|
51
|
+
|
|
52
|
+
# %%
|
|
53
|
+
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
|
|
54
|
+
brainmass.viz.plot_timeseries(res['S_e'], ts=res['ts'], ax=axes[0])
|
|
55
|
+
axes[0].set_title('Excitatory gating S_e')
|
|
56
|
+
brainmass.viz.plot_timeseries(res['rate_e'], ts=res['ts'], ax=axes[1])
|
|
57
|
+
axes[1].set_title('Excitatory rate H_e (Hz)')
|
|
58
|
+
plt.tight_layout()
|
|
59
|
+
plt.show()
|
|
60
|
+
|
|
61
|
+
# %% [markdown]
|
|
62
|
+
# ## Try it: vary the feedback inhibition `J_i`
|
|
63
|
+
#
|
|
64
|
+
# The feedback-inhibition weight `J_i` sets the E-I balance. Stronger inhibition clamps the excitatory rate lower; weaker inhibition lets it climb. We report the settled excitatory rate.
|
|
65
|
+
|
|
66
|
+
# %%
|
|
67
|
+
for J_i in [0.5, 1.0, 1.5]:
|
|
68
|
+
m = brainmass.WongWangExcInhStep(in_size=1, J_i=J_i, G=2.0)
|
|
69
|
+
r = brainmass.Simulator(m, dt=0.1 * u.ms).run(
|
|
70
|
+
3000. * u.ms, monitors={'rate_e': lambda m: m.H_e()})
|
|
71
|
+
rate = float(u.get_magnitude(r['rate_e'])[-1, 0])
|
|
72
|
+
print(f'J_i = {J_i:.1f} -> resting excitatory rate = {rate:.2f} Hz')
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# Visualization and analysis
|
|
2
|
+
|
|
3
|
+
Use this reference when plotting BrainMass results or computing time-series, functional-connectivity, functional-connectivity-dynamics, and spectral summaries. Keep scientific metric computation in Braintools and use `brainmass.viz` as the thin optional plotting layer.
|
|
4
|
+
|
|
5
|
+
## Plot results
|
|
6
|
+
|
|
7
|
+
`brainmass.viz` imports matplotlib lazily. Install the BrainMass visualization extra before using it; core `brainmass` imports do not require matplotlib.
|
|
8
|
+
|
|
9
|
+
| API | Description |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `brainmass.viz.plot_timeseries(signal, ts=None, labels=None, ax=None, ...)` | Plot one or more time-major regional or sensor trajectories; it accepts unit-aware signal and time inputs. |
|
|
12
|
+
| `brainmass.viz.plot_phase_portrait(x, y, ax=None, ...)` | Plot one State variable against another for oscillator or attractor inspection. |
|
|
13
|
+
| `brainmass.viz.plot_connectivity(matrix, labels=None, ax=None, ...)` | Plot any square structural, functional, FCD, or regime matrix as a heatmap. |
|
|
14
|
+
| `brainmass.viz.plot_functional_connectivity(data, is_matrix=False, labels=None, ax=None, ...)` | Compute FC from a trajectory or plot an existing matrix when `is_matrix=True`. |
|
|
15
|
+
| `brainmass.viz.plot_power_spectrum(signal, dt, ax=None, loglog=False, ...)` | Compute and plot the PSD of one one-dimensional signal with sampling interval `dt`. |
|
|
16
|
+
|
|
17
|
+
Every helper accepts `ax=` and returns the `matplotlib.axes.Axes` it drew on. Pass axes explicitly when composing figures.
|
|
18
|
+
|
|
19
|
+
## Compute standard summaries
|
|
20
|
+
|
|
21
|
+
Strip units explicitly before a metric that operates on scale-free raw arrays. Keep the sampling interval and labels separately.
|
|
22
|
+
|
|
23
|
+
| API | Description |
|
|
24
|
+
|---|---|
|
|
25
|
+
| `braintools.metric.functional_connectivity(signal)` | Compute pairwise correlation across regions from a `(time, regions)` trajectory. |
|
|
26
|
+
| `braintools.metric.functional_connectivity_dynamics(signal, window_size, step_size)` | Slide an FC window and correlate windowed FC matrices to return an `(n_window, n_window)` FCD matrix. |
|
|
27
|
+
| `braintools.metric.power_spectral_density(signal, dt_ms)` | Return frequencies and PSD for a one-dimensional signal; use a sampling interval in the expected raw unit. |
|
|
28
|
+
| `brainmass.objectives.fc_corr()` | Score correlation between prediction and target FC without manually recomputing the comparison logic. |
|
|
29
|
+
| `brainmass.objectives.fcd_distribution(fcd_matrix, ...)` | Estimate the off-diagonal FCD value distribution used by distributional FCD objectives. |
|
|
30
|
+
|
|
31
|
+
## Canonical analysis workflow
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
import brainmass
|
|
35
|
+
import brainstate
|
|
36
|
+
import brainunit as u
|
|
37
|
+
import braintools
|
|
38
|
+
import numpy as np
|
|
39
|
+
|
|
40
|
+
dt = 0.1 * u.ms
|
|
41
|
+
brainstate.environ.set(dt=dt)
|
|
42
|
+
brainstate.random.seed(0)
|
|
43
|
+
|
|
44
|
+
connectome = brainmass.datasets.load_dataset("example_connectome")
|
|
45
|
+
n_region = connectome.weights.shape[0]
|
|
46
|
+
node = brainmass.HopfStep(
|
|
47
|
+
in_size=n_region,
|
|
48
|
+
a=0.1,
|
|
49
|
+
w=0.3,
|
|
50
|
+
noise_x=brainmass.OUProcess(
|
|
51
|
+
n_region,
|
|
52
|
+
sigma=0.1,
|
|
53
|
+
tau=10.0 * u.ms,
|
|
54
|
+
),
|
|
55
|
+
)
|
|
56
|
+
network = brainmass.Network(
|
|
57
|
+
node,
|
|
58
|
+
conn=connectome.weights,
|
|
59
|
+
distance=connectome.distances,
|
|
60
|
+
speed=10.0 * u.mm / u.ms,
|
|
61
|
+
coupling="diffusive",
|
|
62
|
+
coupled_var="x",
|
|
63
|
+
k=0.5,
|
|
64
|
+
)
|
|
65
|
+
result = brainmass.Simulator(network, dt=dt).run(
|
|
66
|
+
4000.0 * u.ms,
|
|
67
|
+
monitors=lambda model: model.node.x.value,
|
|
68
|
+
transient=400.0 * u.ms,
|
|
69
|
+
sample_every=10,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
signal = u.get_magnitude(result["output"])
|
|
73
|
+
fc = braintools.metric.functional_connectivity(signal)
|
|
74
|
+
fcd = braintools.metric.functional_connectivity_dynamics(
|
|
75
|
+
signal,
|
|
76
|
+
window_size=100,
|
|
77
|
+
step_size=20,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
assert fc.shape == (n_region, n_region)
|
|
81
|
+
assert fcd.ndim == 2 and fcd.shape[0] == fcd.shape[1]
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`sample_every=10` records every 1 ms when `dt=0.1 ms`; use the recorded `ts` difference as the analysis sampling interval rather than the integration `dt`.
|
|
85
|
+
|
|
86
|
+
## Compare with data
|
|
87
|
+
|
|
88
|
+
Use the same preprocessing, region order, duration policy, and sampling rate before comparing summaries.
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
target = brainmass.datasets.load_dataset("example_signal")
|
|
92
|
+
score = brainmass.objectives.fc_corr()(
|
|
93
|
+
signal,
|
|
94
|
+
target.signal,
|
|
95
|
+
)
|
|
96
|
+
assert np.isfinite(float(score))
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Use `as_loss=True` only when the score is passed to a minimizer. A high FC score does not validate spectra, FCD, amplitudes, or parameter plausibility.
|
|
100
|
+
|
|
101
|
+
## Analyze spectra
|
|
102
|
+
|
|
103
|
+
Use one channel at a time unless the metric explicitly accepts multichannel input.
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
record_dt_ms = float(
|
|
107
|
+
(result["ts"][1] - result["ts"][0]).to(u.ms).mantissa
|
|
108
|
+
)
|
|
109
|
+
frequencies, power = braintools.metric.power_spectral_density(
|
|
110
|
+
signal[:, 0],
|
|
111
|
+
record_dt_ms,
|
|
112
|
+
)
|
|
113
|
+
assert frequencies.shape == power.shape
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Convert cycles per millisecond to hertz only when the metric's returned frequency convention requires it. Do not infer a sampling frequency from the number of samples alone.
|
|
117
|
+
|
|
118
|
+
## Common failures
|
|
119
|
+
|
|
120
|
+
- Computing FC over the region axis instead of the time axis.
|
|
121
|
+
- Comparing matrices whose region labels are in different orders.
|
|
122
|
+
- Using integration `dt` after `sample_every` changed the recorded sampling interval.
|
|
123
|
+
- Treating FCD as static FC or fitting the full matrix when the intended target is its off-diagonal distribution.
|
|
124
|
+
- Plotting a unit-bearing `Quantity` by implicit NumPy conversion instead of using `brainmass.viz` or `u.get_magnitude`.
|
|
125
|
+
- Claiming scientific validation from a single summary.
|
|
126
|
+
|
|
127
|
+
## Official sources
|
|
128
|
+
|
|
129
|
+
- `https://brainx.chaobrain.com/brainmass/reference/viz.html`
|
|
130
|
+
- `https://brainx.chaobrain.com/brainmass/howto/analyze_results.html`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: brainpy-state
|
|
3
|
-
description:
|
|
3
|
+
description: Use for point-neuron modeling, from individual neurons to spiking networks with synapses and projections. Use alone for point-neuron studies or together with BrainCell and/or BrainMass when point-neuron dynamics participate in a multiscale model.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# BrainPy-State
|
|
@@ -1,153 +1,68 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: brainx-general-guard
|
|
3
|
-
description:
|
|
3
|
+
description: Use first for every BrainX modeling, simulation, training, review, debugging, or optimization task. Identify every modeling scale explicitly represented, open only the BrainX package skills that own those scales, and keep the implementation BrainX-native.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
#
|
|
6
|
+
# BrainX general guard
|
|
7
7
|
|
|
8
|
-
##
|
|
8
|
+
## Purpose and boundary
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
Three nouns carry the whole framework: State, Module, and Transform.
|
|
12
|
-
**Source mirrored:** https://brainx.chaobrain.com/brainstate/getting_started/thinking_in_brainstate.html
|
|
10
|
+
Open this guard before any package skill for every BrainX modeling task. First identify every modeling scale explicitly represented, then open the package skills that own those scales and keep this guard active as the cross-cutting implementation layer.
|
|
13
11
|
|
|
14
|
-
|
|
15
|
-
BrainState transformations mirror JAX’s, but understand State; reads and writes are threaded through compiled functions automatically.
|
|
16
|
-
**Source mirrored:** https://brainx.chaobrain.com/brainstate/getting_started/thinking_in_brainstate.html
|
|
12
|
+
## Select modeling skills by represented scale
|
|
17
13
|
|
|
18
|
-
|
|
19
|
-
In braincell, every physical quantity carries an explicit unit; passing a bare number where a quantity is expected raises TypeError.
|
|
20
|
-
**Source mirrored:** https://brainx.chaobrain.com/braincell/concepts/units.html
|
|
14
|
+
Select every row supported by the user's task. A single-scale task opens one modeling skill; a multiscale task may open two or all three.
|
|
21
15
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
16
|
+
| The task explicitly represents | Open |
|
|
17
|
+
|---|---|
|
|
18
|
+
| Point neurons, synapses, or point-neuron spiking networks | BrainPy-State |
|
|
19
|
+
| Ions, channels, compartments, or cellular morphology | BrainCell |
|
|
20
|
+
| Aggregate neural populations, local circuits, brain regions, or whole-brain dynamics | BrainMass |
|
|
21
|
+
| Detailed cells connected into a spiking network | BrainCell + BrainPy-State |
|
|
22
|
+
| Point-neuron spiking networks coupled to aggregate regional dynamics | BrainPy-State + BrainMass |
|
|
23
|
+
| Cellular mechanisms coupled to aggregate neural-mass dynamics | BrainCell + BrainMass |
|
|
24
|
+
| Cellular biophysics, point-neuron networks, and aggregate population dynamics interacting in one workflow | BrainCell + BrainPy-State + BrainMass |
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
Use the finest explicitly modeled unit to distinguish adjacent scales: point neurons select BrainPy-State, explicit cellular mechanisms select BrainCell, and aggregate population variables select BrainMass.
|
|
27
27
|
|
|
28
|
+
## Write BrainX-native code
|
|
28
29
|
|
|
29
|
-
|
|
30
|
+
Start from the scientific concept and use the selected BrainX skills to construct the workflow. Avoid raw NumPy or JAX unless at an explicit interoperability boundary or after verifying an API gap.
|
|
30
31
|
|
|
31
|
-
|
|
32
|
-
brainx-general-guard/
|
|
33
|
-
└── brainstate-randomness-reproducibility/
|
|
34
|
-
└── randomness-and-reproducibility.md
|
|
35
|
-
└── advanced-randomness.md
|
|
36
|
-
```
|
|
32
|
+
## Prefer high-level BrainX APIs
|
|
37
33
|
|
|
38
|
-
|
|
34
|
+
Use high-level APIs as the abstraction boundary: simulation code should state the scientific operation while BrainX handles array manipulation, unit propagation, State threading, numerical steps, and infrastructure.
|
|
39
35
|
|
|
40
|
-
|
|
36
|
+
| Need | Prefer |
|
|
37
|
+
|---|---|
|
|
38
|
+
| Physical values, array creation or structure, mathematical operations | BrainUnit quantities and `brainunit.math` |
|
|
39
|
+
| Connectivity, encoding, inputs, initialization, integration, metrics, optimization, surrogate gradients, training, visualization | `braintools.conn`, `input`, `init`, `quad`, `metric`, `optim`, `surrogate`, `trainer`, or `visualize` |
|
|
40
|
+
| Mutable model state, compilation, differentiation, batching, control flow, randomness | `brainstate.State`, `brainstate.nn.Module`, `brainstate.transform`, and `brainstate.random` |
|
|
41
|
+
| Cells, events, networks, mass models, or traces | The corresponding BrainCell, BrainEvent, BrainPy-State, BrainMass, or BrainTrace abstraction |
|
|
41
42
|
|
|
42
|
-
Do not
|
|
43
|
+
Do not let code grow around manual indexing, reshaping, reductions, equations, loops, or bookkeeping. Prefer one named BrainX operation or Module over a chain of generic primitives.
|
|
43
44
|
|
|
44
|
-
|
|
45
|
+
Write custom logic only when it expresses model behavior that the ecosystem does not already provide. Verify the owning skill, reference, or official API page before using an unfamiliar name or signature.
|
|
45
46
|
|
|
46
|
-
Domain routing guard
|
|
47
47
|
|
|
48
|
-
|
|
48
|
+
## Transform stateful execution
|
|
49
49
|
|
|
50
|
-
|
|
50
|
+
Transform the complete stateful operation with `brainstate.transform` whenever practical.
|
|
51
51
|
|
|
52
|
-
|
|
52
|
+
| API | Use |
|
|
53
|
+
|---|---|
|
|
54
|
+
| `brainstate.transform.jit`, `grad`, `vmap` | Compile, differentiate, or batch a complete stateful forward, simulation, or training operation. |
|
|
55
|
+
| `brainstate.transform.for_loop` | Run a fixed time or data sequence when iteration-to-iteration effects live in `State`; it slices leading input axes and stacks per-step outputs. |
|
|
56
|
+
| `brainstate.transform.scan` | Run a sequence when an ordinary explicit carry must pass between iterations. |
|
|
53
57
|
|
|
54
|
-
|
|
58
|
+
Do not use a Python loop for simulation timesteps, recurrent sequences, or other repeated State updates that should execute as one compiled operation. Keep Python loops for static Module construction, configuration, host-side orchestration, and debugging outside the transformed execution path.
|
|
55
59
|
|
|
56
|
-
|
|
60
|
+
Use raw JAX transformations only for pure array or PyTree functions that do not close over BrainState `State`.
|
|
57
61
|
|
|
58
|
-
|
|
59
|
-
import jax
|
|
60
|
-
import jax.numpy as jnp
|
|
61
|
-
import brainstate
|
|
62
|
-
class RunningMean(brainstate.nn.Module):
|
|
63
|
-
def __init__(self):
|
|
64
|
-
super().__init__()
|
|
65
|
-
self.sum = brainstate.HiddenState(jnp.array(0.0))
|
|
66
|
-
self.count = brainstate.HiddenState(jnp.array(0))
|
|
67
|
-
def __call__(self, batch: jax.Array) -> jax.Array:
|
|
68
|
-
self.sum.value += jnp.sum(batch)
|
|
69
|
-
self.count.value += batch.size
|
|
70
|
-
return self.sum.value / self.count.value
|
|
71
|
-
tracker = RunningMean()
|
|
72
|
-
@brainstate.transform.jit
|
|
73
|
-
def update_running_mean(batch: jax.Array) -> jax.Array:
|
|
74
|
-
return tracker(batch)
|
|
75
|
-
for step in range(3):
|
|
76
|
-
data = jnp.arange(4.0) + step
|
|
77
|
-
print(f'step {step}: mean={float(update_running_mean(data)):.2f}')
|
|
78
|
-
float(tracker.sum.value), int(tracker.count.value)
|
|
79
|
-
```
|
|
62
|
+
## Boundaries and common failures
|
|
80
63
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
Use BrainState loop transforms for stateful loops
|
|
87
|
-
|
|
88
|
-
**Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html
|
|
89
|
-
|
|
90
|
-
#### Script
|
|
91
|
-
|
|
92
|
-
```python
|
|
93
|
-
# Example 2: Stateful for_loop
|
|
94
|
-
class Accumulator(brainstate.nn.Module):
|
|
95
|
-
"""Simple accumulator that tracks total and count."""
|
|
96
|
-
def __init__(self):
|
|
97
|
-
super().__init__()
|
|
98
|
-
self.total = brainstate.ShortTermState(jnp.array(0.0))
|
|
99
|
-
self.count = brainstate.ShortTermState(jnp.array(0))
|
|
100
|
-
def process(self, x):
|
|
101
|
-
self.total.value = self.total.value + x
|
|
102
|
-
self.count.value = self.count.value + 1
|
|
103
|
-
return self.total.value / self.count.value # running average
|
|
104
|
-
acc = Accumulator()
|
|
105
|
-
data = jnp.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
|
|
106
|
-
running_averages = for_loop(acc.process, data)
|
|
107
|
-
print("Data:", data)
|
|
108
|
-
print("Running averages:", running_averages)
|
|
109
|
-
print(f"\n Final state: total={acc.total.value}, count={acc.count.value}")
|
|
110
|
-
print(f"Final average: {acc.total.value / acc.count.value}")
|
|
111
|
-
```
|
|
112
|
-
|
|
113
|
-
#### Explanation text
|
|
114
|
-
|
|
115
|
-
Control-flow APIs in brainstate.transform provide JAX-compatible loops and conditionals while safely handling State objects; loop transformations compile to a single JAX primitive, reducing compilation overhead.
|
|
116
|
-
**Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html
|
|
117
|
-
|
|
118
|
-
Use units before biological simulation
|
|
119
|
-
|
|
120
|
-
**Source mirrored:** https://brainx.chaobrain.com/braincell/concepts/units.html
|
|
121
|
-
|
|
122
|
-
#### Script
|
|
123
|
-
|
|
124
|
-
```python
|
|
125
|
-
import numpy as np
|
|
126
|
-
import jax.numpy as jnp
|
|
127
|
-
import brainunit as u
|
|
128
|
-
v_rest = -65.0 * u.mV # scalar
|
|
129
|
-
dt = 0.1 * u.ms
|
|
130
|
-
lengths = np.array([10.5, 20.0]) * u.um # numpy array
|
|
131
|
-
coords = jnp.zeros((10, 3)) * u.um # JAX array
|
|
132
|
-
radii = [2.0, 3.0, 4.0] * u.um # list
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
#### Explanation text
|
|
136
|
-
|
|
137
|
-
Silent unit mismatches are one of the most common and hardest-to-find bugs in neural modeling; BrainCell requires units everywhere and catches dimensional errors immediately.
|
|
138
|
-
**Source mirrored:** https://brainx.chaobrain.com/braincell/concepts/units.html
|
|
139
|
-
|
|
140
|
-
## Common mistakes -> Fix
|
|
141
|
-
|
|
142
|
-
• writing random NumPy simulation code -> route first to BrainState / BrainCell / BrainUnit.
|
|
143
|
-
• using raw jax.jit on stateful BrainState modules -> use brainstate.transform.jit; raw jax.jit requires manual state threading.
|
|
144
|
-
• Python for-loop around state updates when compiling/scanning -> use BrainState scan, for_loop, or control-flow transform.
|
|
145
|
-
• passing bare floats into BrainCell mechanisms -> attach brainunit units.
|
|
146
|
-
• treating BrainCell as generic ODE code -> use cells, ions, channels, mechanisms, and integrators.
|
|
147
|
-
• writing custom ion channel first -> check built-in braincell.channel list first.
|
|
148
|
-
• inventing APIs -> open the official example/source first; do not fabricate a standalone script when no official pattern exists.
|
|
149
|
-
• loading install guidance for ordinary modeling -> use `skills/brainx-install/SKILL.md` only after install/setup/backend/package evidence appears.
|
|
150
|
-
|
|
151
|
-
## Script references
|
|
152
|
-
|
|
153
|
-
None. This guard has no standalone script reference; its compact guard examples remain inline.
|
|
64
|
+
- Generic NumPy or JAX used as the starting architecture for a BrainX simulation.
|
|
65
|
+
- Manual array or mathematical machinery that duplicates BrainUnit or BrainTools.
|
|
66
|
+
- Python loops around stateful simulation or training steps.
|
|
67
|
+
- Raw `jax.jit`, `jax.grad`, or `jax.vmap` applied to State-aware code.
|
|
68
|
+
- Fabricated APIs or signatures accepted without checking the owning documentation.
|