brainx-skill 1.0.8 → 1.0.10
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 +52 -118
- package/skills/brainx-install/SKILL.md +7 -4
- 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,87 @@
|
|
|
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
|
+
## Never inspect BrainX packages in the venv. for knowledge, ONLY check presence
|
|
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
|
+
Treat BrainX packages in the active virtual environment only as execution dependencies, never as sources of modeling knowledge.
|
|
13
11
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
**
|
|
12
|
+
- **ONLY check presence.** Determine whether each required BrainX package is present, then stop inspecting the environment.
|
|
13
|
+
- **NEVER investigate installed content.** Do not enumerate package files, modules, symbols, signatures, docstrings, runtime definitions, or object internals.
|
|
14
|
+
- **NEVER read installed source code.** Do not open or read any BrainX source code in the virtual environment.
|
|
17
15
|
|
|
18
|
-
• BrainUnit / BrainCell unit guard
|
|
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
|
|
21
16
|
|
|
22
|
-
|
|
23
|
-
A mechanism is anything installed on a cell that affects dynamics; in braincell, mechanisms are declarative and describe what to install without touching JAX, time, or runtime state.
|
|
24
|
-
**Source mirrored:** https://brainx.chaobrain.com/braincell/concepts/mechanisms.html
|
|
17
|
+
## Study modeling skills and task-relevant scripts
|
|
25
18
|
|
|
26
|
-
|
|
19
|
+
1. Treat the selected modeling skills as the authoritative guide to BrainX modeling, dive deep into the skill.
|
|
20
|
+
2. Follow the skill's exact routing instructions. Open every reference that are likely relevant by the user's task.
|
|
21
|
+
3. Identify the example scripts referenced by the skill or its routed references. Open and study every script that is highly related to the user's task.
|
|
22
|
+
4. Trace each relevant script end to end.
|
|
23
|
+
5. Derive the implementation from those canonical patterns, then adapt only the parts required by the user's scientific model.
|
|
27
24
|
|
|
28
25
|
|
|
29
|
-
## Conditional reference routing
|
|
30
26
|
|
|
31
|
-
|
|
32
|
-
brainx-general-guard/
|
|
33
|
-
└── brainstate-randomness-reproducibility/
|
|
34
|
-
└── randomness-and-reproducibility.md
|
|
35
|
-
└── advanced-randomness.md
|
|
36
|
-
```
|
|
27
|
+
## Select modeling skills by represented scale
|
|
37
28
|
|
|
38
|
-
|
|
29
|
+
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.
|
|
39
30
|
|
|
40
|
-
|
|
31
|
+
| The task explicitly represents | Open |
|
|
32
|
+
|---|---|
|
|
33
|
+
| Point neurons, synapses, or point-neuron spiking networks | BrainPy-State |
|
|
34
|
+
| Ions, channels, compartments, or cellular morphology | BrainCell |
|
|
35
|
+
| Aggregate neural populations, local circuits, brain regions, or whole-brain dynamics | BrainMass |
|
|
36
|
+
| Detailed cells connected into a spiking network | BrainCell + BrainPy-State |
|
|
37
|
+
| Point-neuron spiking networks coupled to aggregate regional dynamics | BrainPy-State + BrainMass |
|
|
38
|
+
| Cellular mechanisms coupled to aggregate neural-mass dynamics | BrainCell + BrainMass |
|
|
39
|
+
| Cellular biophysics, point-neuron networks, and aggregate population dynamics interacting in one workflow | BrainCell + BrainPy-State + BrainMass |
|
|
41
40
|
|
|
42
|
-
|
|
41
|
+
## Write BrainX-native code
|
|
43
42
|
|
|
44
|
-
|
|
43
|
+
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.
|
|
45
44
|
|
|
46
|
-
|
|
45
|
+
## Prefer high-level BrainX APIs
|
|
47
46
|
|
|
48
|
-
|
|
47
|
+
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.
|
|
49
48
|
|
|
50
|
-
|
|
49
|
+
| Need | Prefer |
|
|
50
|
+
|---|---|
|
|
51
|
+
| array creation or structure, mathematical operations | BrainUnit quantities and `brainunit.math` |
|
|
52
|
+
| Connectivity, encoding, inputs, initialization, integration, metrics, optimization, surrogate gradients, training, visualization | `braintools` |
|
|
51
53
|
|
|
52
|
-
Use BrainState JIT for stateful modules
|
|
53
54
|
|
|
54
|
-
|
|
55
|
+
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.
|
|
55
56
|
|
|
56
|
-
|
|
57
|
+
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.
|
|
57
58
|
|
|
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
|
-
```
|
|
59
|
+
## Keep plotting code short without lowering figure quality
|
|
80
60
|
|
|
81
|
-
|
|
61
|
+
Use high-level `matplotlib.pyplot` APIs for standard scientific plots. Prefer a compact sequence of `plt.figure()`, `plt.plot()`, labeling, layout, and display calls over low-level Figure, Axes, Artist, or styling machinery when the high-level API expresses the same figure clearly.
|
|
82
62
|
|
|
83
|
-
brainstate.transform.jit understands State objects and automatically wires read/write traces into the compiled function; raw jax.jit requires explicitly splitting and merging module state.
|
|
84
|
-
**Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
|
|
85
63
|
|
|
86
|
-
|
|
64
|
+
Brevity applies to the code, not the figure's scientific content or visual quality.
|
|
87
65
|
|
|
88
|
-
**Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html
|
|
89
66
|
|
|
90
|
-
|
|
67
|
+
## Transform stateful execution
|
|
91
68
|
|
|
92
|
-
|
|
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
|
-
```
|
|
69
|
+
Transform the complete stateful operation with `brainstate.transform` whenever practical.
|
|
112
70
|
|
|
113
|
-
|
|
71
|
+
| API | Use |
|
|
72
|
+
|---|---|
|
|
73
|
+
| `brainstate.transform.jit`, `grad`, `vmap` | Compile, differentiate, or batch a complete stateful forward, simulation, or training operation. |
|
|
74
|
+
| `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. |
|
|
75
|
+
| `brainstate.transform.scan` | Run a sequence when an ordinary explicit carry must pass between iterations. |
|
|
114
76
|
|
|
115
|
-
|
|
116
|
-
**Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html
|
|
77
|
+
Do not use a Python loop for simulation timesteps, recurrent sequences, or other repeated State updates that should execute as one compiled operation.
|
|
117
78
|
|
|
118
|
-
Use
|
|
79
|
+
Use raw JAX transformations only for pure array or PyTree functions that do not close over BrainState `State`.
|
|
119
80
|
|
|
120
|
-
|
|
81
|
+
## Boundaries and common failures
|
|
121
82
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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.
|
|
83
|
+
- Generic NumPy or JAX used as the starting architecture for a BrainX simulation.
|
|
84
|
+
- Manual array or mathematical machinery that duplicates BrainUnit or BrainTools.
|
|
85
|
+
- Python loops around stateful simulation or training steps.
|
|
86
|
+
- Raw `jax.jit`, `jax.grad`, or `jax.vmap` applied to State-aware code.
|
|
87
|
+
- Fabricated APIs or signatures accepted without checking the owning documentation.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: brainx-install
|
|
3
|
-
description: "
|
|
3
|
+
description: " Gently check whether the BrainX meta-package is installed in the intended Python environment; if it is absent, open this skill. use this skill to install, set up, upgrade, downgrade, pin, migrate, uninstall, or clean up BrainX."
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# BrainX Install
|
|
@@ -67,7 +67,7 @@ Determine whether the intended installation is for:
|
|
|
67
67
|
- `cuda13`
|
|
68
68
|
- `tpu`
|
|
69
69
|
|
|
70
|
-
Do not treat detected hardware as the user's choice. If the target is unstated, implied, contradictory, or unclear, question the user directly and persistently until they explicitly choose one device target.
|
|
70
|
+
Do not treat detected hardware as the user's choice. If the target is unstated, implied, contradictory, or unclear, question the user directly and persistently until they explicitly choose one device target.
|
|
71
71
|
|
|
72
72
|
Reflect the understood requirement back to the user before release selection. Use wording such as:
|
|
73
73
|
|
|
@@ -161,7 +161,7 @@ Verification passes only when:
|
|
|
161
161
|
|
|
162
162
|
Do not modify manifests, lockfiles, requirements files, or unrelated environments.
|
|
163
163
|
|
|
164
|
-
## 7. Report
|
|
164
|
+
## 7. Report and Post-install handoff
|
|
165
165
|
|
|
166
166
|
Report:
|
|
167
167
|
|
|
@@ -171,7 +171,10 @@ Report:
|
|
|
171
171
|
- verification command output;
|
|
172
172
|
- final status: `PASS` or `FAIL`, with the reason.
|
|
173
173
|
|
|
174
|
-
|
|
174
|
+
After reporting a `PASS`, explicitly tell the user:
|
|
175
|
+
|
|
176
|
+
> This session is for installation of the BrainX package. Installation is complete; Please open another codex chat so that the context is clean
|
|
177
|
+
|
|
175
178
|
|
|
176
179
|
## Official Commands to use
|
|
177
180
|
|