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,121 @@
|
|
|
1
|
+
# BrainMass noise processes
|
|
2
|
+
|
|
3
|
+
Use this reference when choosing a stochastic spectrum or correlation structure, attaching noise to a model, generating noise directly, or validating stochastic units, State, batches, and reproducibility.
|
|
4
|
+
|
|
5
|
+
## Choose a process
|
|
6
|
+
|
|
7
|
+
Use the simplest spectrum that expresses the scientific assumption.
|
|
8
|
+
|
|
9
|
+
| API | Description |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `brainmass.GaussianNoise(in_size, mean=..., sigma=...)` | Use for independent Gaussian samples at every step; it is stateless and has a flat spectrum. |
|
|
12
|
+
| `brainmass.WhiteNoise(...)` | Use as the semantic alias of `GaussianNoise` when the white-noise assumption should be explicit. |
|
|
13
|
+
| `brainmass.OUProcess(in_size, mean=..., sigma=..., tau=...)` | Use for stationary mean-reverting drive with exponential autocorrelation; larger `tau` produces slower, smoother fluctuations. |
|
|
14
|
+
| `brainmass.BrownianNoise(in_size, sigma=...)` | Use for a stateful random walk with a `1/f^2` spectrum and variance that grows over time. |
|
|
15
|
+
| `brainmass.ColoredNoise(in_size, sigma=..., beta=...)` | Use when a custom `1/f^beta` spectrum is required. |
|
|
16
|
+
| `brainmass.PinkNoise(...)` | Use for the `beta=1` convenience form with a `1/f` spectrum. |
|
|
17
|
+
| `brainmass.BlueNoise(...)` | Use for the `beta=-1` convenience form with high-frequency emphasis. |
|
|
18
|
+
| `brainmass.VioletNoise(...)` | Use for the `beta=-2` convenience form with stronger high-frequency emphasis. |
|
|
19
|
+
|
|
20
|
+
`Noise` is the abstract common contract; instantiate a concrete process. Set `sigma` in the same unit as the model variable receiving the noise.
|
|
21
|
+
|
|
22
|
+
## Attach noise to a model
|
|
23
|
+
|
|
24
|
+
Noise is sampled inside `update()`, so attach it to the model's documented noise parameter and leave the `Simulator` call unchanged.
|
|
25
|
+
|
|
26
|
+
| API | Description |
|
|
27
|
+
|---|---|
|
|
28
|
+
| `brainstate.random.seed(seed)` | Reset the BrainState random stream before any stochastic construction or run that must be reproducible. |
|
|
29
|
+
| `<Model>Step(..., noise_<var>=process)` | Attach a process to the documented State component during construction. |
|
|
30
|
+
| `Simulator.run(..., batch_size=N)` | Initialize `N` independent model and noise realizations and return a time-major trajectory with a batch axis. |
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import brainmass
|
|
34
|
+
import brainstate
|
|
35
|
+
import brainunit as u
|
|
36
|
+
import jax.numpy as jnp
|
|
37
|
+
|
|
38
|
+
def noisy_run(seed):
|
|
39
|
+
brainstate.random.seed(seed)
|
|
40
|
+
node = brainmass.HopfStep(
|
|
41
|
+
in_size=1,
|
|
42
|
+
a=-0.05,
|
|
43
|
+
w=0.3,
|
|
44
|
+
noise_x=brainmass.OUProcess(
|
|
45
|
+
in_size=1,
|
|
46
|
+
sigma=0.1,
|
|
47
|
+
tau=20.0 * u.ms,
|
|
48
|
+
),
|
|
49
|
+
)
|
|
50
|
+
return brainmass.Simulator(node, dt=0.1 * u.ms).run(
|
|
51
|
+
100.0 * u.ms,
|
|
52
|
+
monitors=["x"],
|
|
53
|
+
)["x"]
|
|
54
|
+
|
|
55
|
+
first = noisy_run(7)
|
|
56
|
+
replay = noisy_run(7)
|
|
57
|
+
different = noisy_run(8)
|
|
58
|
+
|
|
59
|
+
assert jnp.allclose(first, replay)
|
|
60
|
+
assert not jnp.allclose(first, different)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Seed before each run whose exact stream matters. Seeding once does not make later calls reuse the same draws.
|
|
64
|
+
|
|
65
|
+
## Run an ensemble
|
|
66
|
+
|
|
67
|
+
Use `batch_size` when uncertainty across realizations is part of the result. The output ordering is time, then batch, then the model's region shape.
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
brainstate.random.seed(2)
|
|
71
|
+
node = brainmass.HopfStep(
|
|
72
|
+
in_size=4,
|
|
73
|
+
a=-0.05,
|
|
74
|
+
w=0.3,
|
|
75
|
+
noise_x=brainmass.OUProcess(4, sigma=0.12, tau=20.0 * u.ms),
|
|
76
|
+
)
|
|
77
|
+
ensemble = brainmass.Simulator(node, dt=0.1 * u.ms).run(
|
|
78
|
+
200.0 * u.ms,
|
|
79
|
+
monitors=["x"],
|
|
80
|
+
batch_size=12,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
assert ensemble["x"].shape == (2000, 12, 4)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Use distributions across the batch dimension; do not report one stochastic trace as an ensemble statistic.
|
|
87
|
+
|
|
88
|
+
## Generate noise directly
|
|
89
|
+
|
|
90
|
+
Use a noise process as the `Simulator` model when a workflow needs a standalone drive or a spectral check. With `monitors=None`, `Simulator` stores the return from `update()` under `"output"`.
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
process = brainmass.OUProcess(
|
|
94
|
+
in_size=3,
|
|
95
|
+
sigma=0.5 * u.Hz,
|
|
96
|
+
tau=50.0 * u.ms,
|
|
97
|
+
)
|
|
98
|
+
samples = brainmass.Simulator(process, dt=0.1 * u.ms).run(
|
|
99
|
+
100.0 * u.ms,
|
|
100
|
+
monitors=None,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
assert samples["output"].shape == (1000, 3)
|
|
104
|
+
assert u.get_unit(samples["output"]) == u.Hz
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Stateless Gaussian noise needs no persistent process State. OU, Brownian, and colored processes do.
|
|
108
|
+
|
|
109
|
+
## Common failures
|
|
110
|
+
|
|
111
|
+
- Passing noise to `Simulator.run()` instead of the model constructor.
|
|
112
|
+
- Guessing a generic `noise=` attribute when the model documents `noise_x`, `noise_E`, or another component-specific parameter.
|
|
113
|
+
- Using unitless `sigma` for a unit-bearing State without confirming that the model permits it.
|
|
114
|
+
- Treating Brownian noise as stationary.
|
|
115
|
+
- Comparing noisy runs without controlling the random stream.
|
|
116
|
+
- Reading `(time, batch, regions)` as batch-major output.
|
|
117
|
+
|
|
118
|
+
## Official sources
|
|
119
|
+
|
|
120
|
+
- `https://brainx.chaobrain.com/brainmass/reference/noise.html`
|
|
121
|
+
- `https://brainx.chaobrain.com/brainmass/tutorials/03_noise.html`
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# Parameter sweeps and regime analysis
|
|
2
|
+
|
|
3
|
+
Use this reference when mapping regimes, sensitivities, or identifiability over a fixed parameter grid. Use `Fitter` instead when the task is to minimize one target objective rather than characterize the landscape.
|
|
4
|
+
|
|
5
|
+
## Choose sweep or fit
|
|
6
|
+
|
|
7
|
+
| Goal | Use |
|
|
8
|
+
|---|---|
|
|
9
|
+
| Visualize a bifurcation, regime boundary, sensitivity, or multiple equivalent solutions | Parameter sweep |
|
|
10
|
+
| Recover parameters that minimize one differentiable target | Gradient `Fitter` |
|
|
11
|
+
| Optimize a non-differentiable target without exhaustively mapping the grid | Gradient-free `Fitter` |
|
|
12
|
+
|
|
13
|
+
Return one scalar or fixed-shape scientific summary per grid point. Avoid retaining full trajectories unless they are required downstream.
|
|
14
|
+
|
|
15
|
+
## Run a one-dimensional sweep
|
|
16
|
+
|
|
17
|
+
Construct the model inside the mapped function so BrainState can trace one independent simulation per parameter value.
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
import brainmass
|
|
21
|
+
import brainstate
|
|
22
|
+
import brainunit as u
|
|
23
|
+
import braintools
|
|
24
|
+
import jax.numpy as jnp
|
|
25
|
+
|
|
26
|
+
def amplitude_for(a):
|
|
27
|
+
node = brainmass.HopfStep(
|
|
28
|
+
in_size=1,
|
|
29
|
+
a=a,
|
|
30
|
+
w=0.3,
|
|
31
|
+
init_x=braintools.init.Constant(0.5),
|
|
32
|
+
)
|
|
33
|
+
result = brainmass.Simulator(node, dt=0.1 * u.ms).run(
|
|
34
|
+
150.0 * u.ms,
|
|
35
|
+
monitors=["x"],
|
|
36
|
+
transient=50.0 * u.ms,
|
|
37
|
+
)
|
|
38
|
+
x = u.get_magnitude(result["x"])[:, 0]
|
|
39
|
+
return jnp.sqrt(jnp.mean(x**2)) * jnp.sqrt(2.0)
|
|
40
|
+
|
|
41
|
+
a_values = jnp.linspace(0.0, 1.5, 16)
|
|
42
|
+
amplitudes = brainstate.transform.vmap(amplitude_for)(a_values)
|
|
43
|
+
|
|
44
|
+
assert amplitudes.shape == a_values.shape
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The mapped function must return the same PyTree structure and leaf shapes for every point.
|
|
48
|
+
|
|
49
|
+
## Run a two-dimensional grid
|
|
50
|
+
|
|
51
|
+
Flatten coordinate grids, map all coordinate arrays together, then reshape the fixed-shape result back to grid order.
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
a_grid = jnp.linspace(0.1, 1.5, 6)
|
|
55
|
+
w_grid = jnp.linspace(0.1, 0.6, 5)
|
|
56
|
+
aa, ww = jnp.meshgrid(a_grid, w_grid, indexing="ij")
|
|
57
|
+
|
|
58
|
+
def amplitude_for_pair(a, w):
|
|
59
|
+
node = brainmass.HopfStep(
|
|
60
|
+
in_size=1,
|
|
61
|
+
a=a,
|
|
62
|
+
w=w,
|
|
63
|
+
init_x=braintools.init.Constant(0.5),
|
|
64
|
+
)
|
|
65
|
+
result = brainmass.Simulator(node, dt=0.1 * u.ms).run(
|
|
66
|
+
150.0 * u.ms,
|
|
67
|
+
monitors=["x"],
|
|
68
|
+
transient=50.0 * u.ms,
|
|
69
|
+
)
|
|
70
|
+
x = u.get_magnitude(result["x"])[:, 0]
|
|
71
|
+
return jnp.sqrt(jnp.mean(x**2)) * jnp.sqrt(2.0)
|
|
72
|
+
|
|
73
|
+
flat = brainstate.transform.vmap(amplitude_for_pair)(
|
|
74
|
+
aa.reshape(-1),
|
|
75
|
+
ww.reshape(-1),
|
|
76
|
+
)
|
|
77
|
+
grid = flat.reshape(aa.shape)
|
|
78
|
+
assert grid.shape == (6, 5)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Preserve `indexing="ij"` and record axis values with the reshaped result. A heatmap without physical axis values is not a reproducible regime map.
|
|
82
|
+
|
|
83
|
+
## Sweep a delayed network
|
|
84
|
+
|
|
85
|
+
Set global `dt` before `vmap` traces construction of each delayed `Network`.
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
brainstate.environ.set(dt=0.1 * u.ms)
|
|
89
|
+
connectome = brainmass.datasets.load_dataset("example_connectome")
|
|
90
|
+
|
|
91
|
+
def mean_activity_for(k):
|
|
92
|
+
n_region = connectome.weights.shape[0]
|
|
93
|
+
node = brainmass.HopfStep(
|
|
94
|
+
in_size=n_region,
|
|
95
|
+
a=0.2,
|
|
96
|
+
w=0.3,
|
|
97
|
+
init_x=braintools.init.Constant(0.3),
|
|
98
|
+
)
|
|
99
|
+
network = brainmass.Network(
|
|
100
|
+
node,
|
|
101
|
+
conn=connectome.weights,
|
|
102
|
+
distance=connectome.distances,
|
|
103
|
+
speed=10.0 * u.mm / u.ms,
|
|
104
|
+
coupling="diffusive",
|
|
105
|
+
coupled_var="x",
|
|
106
|
+
k=k,
|
|
107
|
+
)
|
|
108
|
+
output = brainmass.Simulator(network, dt=0.1 * u.ms).run(
|
|
109
|
+
600.0 * u.ms,
|
|
110
|
+
monitors=lambda model: model.node.x.value,
|
|
111
|
+
transient=100.0 * u.ms,
|
|
112
|
+
)["output"]
|
|
113
|
+
return jnp.mean(jnp.abs(u.get_magnitude(output)))
|
|
114
|
+
|
|
115
|
+
k_values = jnp.linspace(0.0, 1.5, 8)
|
|
116
|
+
summary = brainstate.transform.vmap(mean_activity_for)(k_values)
|
|
117
|
+
assert summary.shape == k_values.shape
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Use FC, FCD, spectrum, amplitude, synchrony, or another domain summary when mean absolute activity does not answer the scientific question.
|
|
121
|
+
|
|
122
|
+
## Store results
|
|
123
|
+
|
|
124
|
+
Keep coordinate arrays, summary arrays, units, model identity, fixed parameters, `dt`, duration, transient, seed, and code version together. Convert flattened grids to long-form columns only after preserving the original axis ordering.
|
|
125
|
+
|
|
126
|
+
Seed stochastic sweeps deliberately. One common seed across parameter values reduces random differences but couples their noise realization; independent seeds estimate uncertainty instead. State which design was used.
|
|
127
|
+
|
|
128
|
+
## Official source
|
|
129
|
+
|
|
130
|
+
- `https://brainx.chaobrain.com/brainmass/howto/parameter_sweeps.html`
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""Reference script mirrored from:
|
|
2
|
+
https://brainx.chaobrain.com/brainmass/gallery/case_studies/eeg_fitting.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
|
+
# Hidden setup cell (imports, deterministic seed, global dt).
|
|
11
|
+
# %matplotlib inline
|
|
12
|
+
import brainmass
|
|
13
|
+
import brainstate
|
|
14
|
+
import braintools
|
|
15
|
+
import brainunit as u
|
|
16
|
+
import jax
|
|
17
|
+
import jax.numpy as jnp
|
|
18
|
+
import numpy as np
|
|
19
|
+
import matplotlib.pyplot as plt
|
|
20
|
+
|
|
21
|
+
brainstate.random.seed(0)
|
|
22
|
+
brainstate.environ.set(dt=0.1 * u.ms)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# %% [markdown]
|
|
26
|
+
# # Fitting an EEG Model with Gradients
|
|
27
|
+
#
|
|
28
|
+
# Whole-brain models have free parameters — coupling strengths, time constants, drive levels —
|
|
29
|
+
# that must be **fit** so the model reproduces a measured signal. Historically this meant a
|
|
30
|
+
# hand-rolled training loop copy-pasted into every script. This case study consolidates that
|
|
31
|
+
# pattern into the one {class}`~brainmass.Fitter` API: *write the objective once, swap optimizer
|
|
32
|
+
# backends.*
|
|
33
|
+
#
|
|
34
|
+
# We fit a {class}`~brainmass.JansenRitStep` cortical-column model — the canonical generator of
|
|
35
|
+
# EEG rhythms — so that the **oscillation amplitude** of its EEG output matches a target.
|
|
36
|
+
#
|
|
37
|
+
# :::{important}
|
|
38
|
+
# **Fit a scalar summary, not the raw waveform.** A gradient fitter that targets a raw
|
|
39
|
+
# oscillatory time series fails: the model and target drift out of phase, the point-by-point RMSE
|
|
40
|
+
# becomes flat/degenerate, and the gradient collapses to `nan`. The robust target is a **scalar
|
|
41
|
+
# feature** of the signal — here the settled EEG oscillation amplitude. (The same lesson holds for
|
|
42
|
+
# FC, spectral peak, or any phase-invariant summary.)
|
|
43
|
+
# :::
|
|
44
|
+
#
|
|
45
|
+
# **Source:** consolidates the hand-rolled `ModelFitting` EEG/MEG fitting scripts (Jansen-Rit
|
|
46
|
+
# column driven to a recorded target) into {class}`~brainmass.Fitter`. Self-contained: the
|
|
47
|
+
# "recorded" target is generated synthetically from a known ground-truth parameter, so the fit has
|
|
48
|
+
# a checkable answer and needs no downloads.
|
|
49
|
+
|
|
50
|
+
# %% [markdown]
|
|
51
|
+
# ## 1. The Jansen-Rit EEG model
|
|
52
|
+
#
|
|
53
|
+
# A {class}`~brainmass.JansenRitStep` is a three-population (pyramidal / excitatory / inhibitory)
|
|
54
|
+
# cortical column whose `eeg()` observable (`E − I`, in mV) oscillates in the alpha band under
|
|
55
|
+
# constant excitatory drive. The dimensionless **connectivity constant `C`** scales the
|
|
56
|
+
# intracortical excitatory/inhibitory loops and strongly controls the amplitude of the rhythm; we
|
|
57
|
+
# treat it as the unknown to recover. (We fit a dimensionless parameter so the loss stays a plain
|
|
58
|
+
# scalar — the same reason the gradient case studies fit `a` or `k`.)
|
|
59
|
+
#
|
|
60
|
+
# First, a quick look at the EEG the model produces.
|
|
61
|
+
|
|
62
|
+
# %%
|
|
63
|
+
def run_jr(C, *, duration=600.0 * u.ms, seed=0):
|
|
64
|
+
"""Simulate one Jansen-Rit column and return (time, EEG trace in mV)."""
|
|
65
|
+
brainstate.random.seed(seed)
|
|
66
|
+
col = brainmass.JansenRitStep(in_size=1, C=C)
|
|
67
|
+
sim = brainmass.Simulator(col, dt=0.1 * u.ms)
|
|
68
|
+
res = sim.run(
|
|
69
|
+
duration,
|
|
70
|
+
inputs=lambda i, t: (0. * u.mV, 220. * u.Hz, 0. * u.mV), # constant excitatory drive
|
|
71
|
+
monitors=lambda m: m.eeg(),
|
|
72
|
+
transient=200.0 * u.ms,
|
|
73
|
+
)
|
|
74
|
+
return res['ts'], res['output']
|
|
75
|
+
|
|
76
|
+
ts, eeg = run_jr(C=135.0) # 135 is the canonical Jansen-Rit value
|
|
77
|
+
fig, ax = plt.subplots(figsize=(9, 3.5))
|
|
78
|
+
brainmass.viz.plot_timeseries(eeg, ts=ts, ax=ax)
|
|
79
|
+
ax.set_title('Jansen-Rit EEG output (C = 135)')
|
|
80
|
+
ax.set_ylabel('EEG (mV)')
|
|
81
|
+
plt.tight_layout()
|
|
82
|
+
plt.show()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# %% [markdown]
|
|
86
|
+
# ## 2. The target and the scalar objective
|
|
87
|
+
#
|
|
88
|
+
# Our "recording" is a Jansen-Rit EEG generated with a **ground-truth** `C* = 150`. We reduce both
|
|
89
|
+
# prediction and target to a single phase-invariant feature — the **RMS amplitude** of the settled
|
|
90
|
+
# oscillation — and fit `C` to match it. Because the amplitude grows smoothly and monotonically
|
|
91
|
+
# with `C`, the loss surface is well conditioned for gradient descent.
|
|
92
|
+
|
|
93
|
+
# %%
|
|
94
|
+
def rms_amplitude(eeg_trace):
|
|
95
|
+
"""Phase-invariant scalar feature: RMS of the (de-meaned) EEG, in mV (dimensionless number)."""
|
|
96
|
+
x = u.get_magnitude(eeg_trace)
|
|
97
|
+
x = x - jnp.mean(x)
|
|
98
|
+
return jnp.sqrt(jnp.mean(x ** 2))
|
|
99
|
+
|
|
100
|
+
C_TRUE = 150.0
|
|
101
|
+
_, eeg_target = run_jr(C=C_TRUE, seed=7)
|
|
102
|
+
target_amp = rms_amplitude(eeg_target)
|
|
103
|
+
print(f"target RMS amplitude (C*={C_TRUE}): {float(target_amp):.4f} mV")
|
|
104
|
+
|
|
105
|
+
# Amplitude grows smoothly with C -> a well-conditioned scalar loss surface.
|
|
106
|
+
c_grid = np.linspace(110, 170, 7)
|
|
107
|
+
amps = [float(rms_amplitude(run_jr(C=c)[1])) for c in c_grid]
|
|
108
|
+
fig, ax = plt.subplots(figsize=(6, 3.5))
|
|
109
|
+
ax.plot(c_grid, amps, 'o-')
|
|
110
|
+
ax.axhline(float(target_amp), color='crimson', ls='--', label='target')
|
|
111
|
+
ax.axvline(C_TRUE, color='grey', ls=':')
|
|
112
|
+
ax.set_xlabel('C (connectivity constant)'); ax.set_ylabel('RMS EEG amplitude (mV)')
|
|
113
|
+
ax.set_title('Scalar loss feature is smooth & monotone'); ax.legend()
|
|
114
|
+
plt.tight_layout()
|
|
115
|
+
plt.show()
|
|
116
|
+
|
|
117
|
+
# %% [markdown]
|
|
118
|
+
# ## 3. Fit with the gradient backend
|
|
119
|
+
#
|
|
120
|
+
# We mark `C` trainable with a {class}`~brainstate.nn.Param` and hand {class}`~brainmass.Fitter`
|
|
121
|
+
# a `loss_fn(model) -> (scalar_loss, aux)`. The loss simulates the column, reduces the EEG to its
|
|
122
|
+
# RMS amplitude, and squares the gap to the target — a scalar that brainmass differentiates
|
|
123
|
+
# straight through the simulation (backprop-through-the-solve). The default `backend='grad'` drives
|
|
124
|
+
# a `braintools.optim` Adam optimizer.
|
|
125
|
+
|
|
126
|
+
# %%
|
|
127
|
+
from brainstate.nn import Param
|
|
128
|
+
|
|
129
|
+
# Trainable column: C starts away from the truth (150) at 115.
|
|
130
|
+
brainstate.random.seed(0)
|
|
131
|
+
column = brainmass.JansenRitStep(in_size=1, C=Param(115.0, fit=True))
|
|
132
|
+
|
|
133
|
+
def loss_fn(model):
|
|
134
|
+
sim = brainmass.Simulator(model, dt=0.1 * u.ms)
|
|
135
|
+
res = sim.run(
|
|
136
|
+
600.0 * u.ms,
|
|
137
|
+
inputs=lambda i, t: (0. * u.mV, 220. * u.Hz, 0. * u.mV),
|
|
138
|
+
monitors=lambda m: m.eeg(),
|
|
139
|
+
transient=200.0 * u.ms,
|
|
140
|
+
)
|
|
141
|
+
amp = rms_amplitude(res['output'])
|
|
142
|
+
loss = (amp - target_amp) ** 2
|
|
143
|
+
return loss, amp
|
|
144
|
+
|
|
145
|
+
fitter = brainmass.Fitter(
|
|
146
|
+
column,
|
|
147
|
+
braintools.optim.Adam(lr=2.0), # C lives on a ~100 scale, so a larger lr
|
|
148
|
+
loss_fn=loss_fn,
|
|
149
|
+
backend='grad',
|
|
150
|
+
)
|
|
151
|
+
result = fitter.fit(n_steps=40, verbose=False)
|
|
152
|
+
|
|
153
|
+
fitted_C = float(result.best_params['C'])
|
|
154
|
+
print(f"true C : {C_TRUE:.2f}")
|
|
155
|
+
print(f"fitted C: {fitted_C:.2f}")
|
|
156
|
+
print(f"best loss: {result.best_loss:.3e}")
|
|
157
|
+
|
|
158
|
+
# %% [markdown]
|
|
159
|
+
# ## 4. Convergence and the recovered EEG
|
|
160
|
+
|
|
161
|
+
# %%
|
|
162
|
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
|
|
163
|
+
ax1.plot(result.history, marker='.')
|
|
164
|
+
ax1.set_yscale('log'); ax1.set_xlabel('optimizer step'); ax1.set_ylabel('loss')
|
|
165
|
+
ax1.set_title('Gradient-fit convergence'); ax1.grid(alpha=0.3)
|
|
166
|
+
|
|
167
|
+
_, eeg_fit = run_jr(C=fitted_C, seed=7)
|
|
168
|
+
brainmass.viz.plot_timeseries(eeg_target, ts=ts, ax=ax2, labels=['target (C*=150)'])
|
|
169
|
+
brainmass.viz.plot_timeseries(eeg_fit, ts=ts, ax=ax2, labels=[f'fitted (C={fitted_C:.1f})'])
|
|
170
|
+
ax2.set_title('Target vs fitted EEG'); ax2.set_ylabel('EEG (mV)'); ax2.legend()
|
|
171
|
+
plt.tight_layout()
|
|
172
|
+
plt.show()
|
|
173
|
+
|
|
174
|
+
# %% [markdown]
|
|
175
|
+
# ## 5. Swapping the backend (no objective rewrite)
|
|
176
|
+
#
|
|
177
|
+
# The payoff of the {class}`~brainmass.Fitter` API: the *same* objective runs under a
|
|
178
|
+
# derivative-free optimizer just by changing `backend`. Gradient-free search is the fallback when a
|
|
179
|
+
# loss is non-differentiable or rugged. Here we give the search an explicit box for `C` and let
|
|
180
|
+
# nevergrad's differential evolution find it.
|
|
181
|
+
|
|
182
|
+
# %%
|
|
183
|
+
try:
|
|
184
|
+
import nevergrad # noqa: F401
|
|
185
|
+
has_ng = True
|
|
186
|
+
except ImportError:
|
|
187
|
+
has_ng = False
|
|
188
|
+
|
|
189
|
+
if has_ng:
|
|
190
|
+
brainstate.random.seed(0)
|
|
191
|
+
column_ng = brainmass.JansenRitStep(in_size=1, C=Param(115.0, fit=True))
|
|
192
|
+
|
|
193
|
+
def loss_fn_ng(model):
|
|
194
|
+
sim = brainmass.Simulator(model, dt=0.1 * u.ms)
|
|
195
|
+
res = sim.run(
|
|
196
|
+
600.0 * u.ms,
|
|
197
|
+
inputs=lambda i, t: (0. * u.mV, 220. * u.Hz, 0. * u.mV),
|
|
198
|
+
monitors=lambda m: m.eeg(), transient=200.0 * u.ms)
|
|
199
|
+
amp = rms_amplitude(res['output'])
|
|
200
|
+
return (amp - target_amp) ** 2, amp
|
|
201
|
+
|
|
202
|
+
fitter_ng = brainmass.Fitter(
|
|
203
|
+
column_ng, {'method': 'DE', 'n_sample': 6},
|
|
204
|
+
loss_fn=loss_fn_ng, backend='nevergrad',
|
|
205
|
+
search_space={'C': (110.0, 170.0)},
|
|
206
|
+
)
|
|
207
|
+
result_ng = fitter_ng.fit(n_steps=8, verbose=False)
|
|
208
|
+
print(f"gradient : C = {fitted_C:.2f}")
|
|
209
|
+
print(f"nevergrad : C = {float(result_ng.best_params['C']):.2f}")
|
|
210
|
+
else:
|
|
211
|
+
print("nevergrad not installed; gradient backend gave C =", f"{fitted_C:.2f}")
|
|
212
|
+
|
|
213
|
+
# %% [markdown]
|
|
214
|
+
# ## Summary
|
|
215
|
+
#
|
|
216
|
+
# We fit a Jansen-Rit EEG model to a target by:
|
|
217
|
+
#
|
|
218
|
+
# 1. picking a **scalar, phase-invariant feature** (RMS amplitude) of the EEG — *never* the raw
|
|
219
|
+
# oscillatory waveform, which makes the gradient degenerate,
|
|
220
|
+
# 2. wrapping the unknown connectivity constant `C` in a trainable {class}`~brainstate.nn.Param`
|
|
221
|
+
# (a dimensionless knob, so the loss stays a plain scalar),
|
|
222
|
+
# 3. handing one `loss_fn` to {class}`~brainmass.Fitter` with `backend='grad'`, which
|
|
223
|
+
# backpropagates through the whole simulation, and
|
|
224
|
+
# 4. recovering the ground-truth `C` and confirming the convergence curve.
|
|
225
|
+
#
|
|
226
|
+
# The same objective ran under a derivative-free backend with a one-line change — the consolidation
|
|
227
|
+
# that replaced the hand-rolled fitting scripts. For fitting a *network* to functional connectivity
|
|
228
|
+
# instead of a single column, swap the scalar feature for
|
|
229
|
+
# {func}`brainmass.objectives.fc_corr(as_loss=True) <brainmass.objectives.fc_corr>` and fit the
|
|
230
|
+
# coupling strength `k`.
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Reference script mirrored from:
|
|
3
|
+
https://brainx.chaobrain.com/brainmass/tutorials/07_gradient_free_fitting.html
|
|
4
|
+
|
|
5
|
+
Purpose:
|
|
6
|
+
Carry the complete gradient-free counterpart to the BrainMass skill's inline
|
|
7
|
+
gradient-fitting example. The objective is written once and fitted with
|
|
8
|
+
Nevergrad differential evolution and SciPy Nelder-Mead.
|
|
9
|
+
|
|
10
|
+
Use this when:
|
|
11
|
+
- The objective is non-differentiable, discrete, jagged, or black-box.
|
|
12
|
+
- A usable gradient is unavailable or unreliable.
|
|
13
|
+
- The task needs a complete `Fitter` example for `nevergrad` or derivative-free
|
|
14
|
+
`scipy` rather than the canonical `grad` path in the skill body.
|
|
15
|
+
|
|
16
|
+
Do not use this when:
|
|
17
|
+
- The objective is differentiable; use the skill body's gradient workflow.
|
|
18
|
+
- The parameters do not have finite transform-derived bounds and no explicit
|
|
19
|
+
`search_space` has been supplied.
|
|
20
|
+
|
|
21
|
+
Operational boundary:
|
|
22
|
+
Gradient-free `Fitter` backends keep the same objective, but they take an
|
|
23
|
+
options dict (or method-name string) instead of a `braintools.optim` instance.
|
|
24
|
+
They also search a bounded box. Here `SigmoidT(0.05, 3.0)` supplies that box.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
import brainmass
|
|
28
|
+
import brainstate
|
|
29
|
+
import braintools
|
|
30
|
+
import brainunit as u
|
|
31
|
+
import jax.numpy as jnp
|
|
32
|
+
from brainstate.nn import Param, SigmoidT
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
brainstate.environ.set(dt=0.1 * u.ms)
|
|
36
|
+
brainstate.random.seed(0)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def make_hopf(a, trainable=False):
|
|
40
|
+
"""Build the tutorial Hopf node, optionally with bounded fitted `a`."""
|
|
41
|
+
a_param = Param(a, t=SigmoidT(0.05, 3.0), fit=True) if trainable else a
|
|
42
|
+
return brainmass.HopfStep(
|
|
43
|
+
in_size=1,
|
|
44
|
+
a=a_param,
|
|
45
|
+
w=0.3,
|
|
46
|
+
init_x=braintools.init.Constant(0.5),
|
|
47
|
+
init_y=braintools.init.Constant(0.0),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def settled_amplitude(node):
|
|
52
|
+
"""Measure the settled Hopf limit-cycle amplitude."""
|
|
53
|
+
res = brainmass.Simulator(node, dt=0.1 * u.ms).run(
|
|
54
|
+
300.0 * u.ms,
|
|
55
|
+
monitors=['x'],
|
|
56
|
+
transient=150.0 * u.ms,
|
|
57
|
+
)
|
|
58
|
+
x = u.get_magnitude(res['x'])
|
|
59
|
+
return jnp.sqrt(jnp.mean(x ** 2)) * jnp.sqrt(2.0)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# Generate the same known target used by the official gradient-fitting tutorial.
|
|
63
|
+
target_amplitude = float(settled_amplitude(make_hopf(1.5)))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def loss_fn(model):
|
|
67
|
+
"""Use the same objective for every optimizer backend."""
|
|
68
|
+
amp = settled_amplitude(model)
|
|
69
|
+
return (amp - target_amplitude) ** 2, amp
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
print(f"target amplitude (true a* = 1.5): {target_amplitude:.4f}")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# Nevergrad: `n_steps` is the number of generations. With `n_sample=6`,
|
|
76
|
+
# 12 generations require roughly 72 forward simulations.
|
|
77
|
+
node = make_hopf(0.1, trainable=True)
|
|
78
|
+
ng_result = brainmass.Fitter(
|
|
79
|
+
node,
|
|
80
|
+
{'method': 'DE', 'n_sample': 6},
|
|
81
|
+
loss_fn=loss_fn,
|
|
82
|
+
backend='nevergrad',
|
|
83
|
+
).fit(n_steps=12)
|
|
84
|
+
|
|
85
|
+
print(
|
|
86
|
+
f"nevergrad: fitted a = {float(ng_result.best_params['a']):.4f}"
|
|
87
|
+
" (true a* = 1.5)"
|
|
88
|
+
)
|
|
89
|
+
print(f" best loss = {ng_result.best_loss:.2e}")
|
|
90
|
+
print(f" simulations = {len(ng_result.history)}")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# SciPy: for this backend `n_steps` is the number of random restarts.
|
|
94
|
+
node = make_hopf(0.1, trainable=True)
|
|
95
|
+
sp_result = brainmass.Fitter(
|
|
96
|
+
node,
|
|
97
|
+
{'method': 'Nelder-Mead'},
|
|
98
|
+
loss_fn=loss_fn,
|
|
99
|
+
backend='scipy',
|
|
100
|
+
).fit(n_steps=3)
|
|
101
|
+
|
|
102
|
+
print(
|
|
103
|
+
f"scipy: fitted a = {float(sp_result.best_params['a']):.4f}"
|
|
104
|
+
" (true a* = 1.5)"
|
|
105
|
+
)
|
|
106
|
+
print(f" best loss = {sp_result.best_loss:.2e}")
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Reference script mirrored from:
|
|
2
|
+
https://brainx.chaobrain.com/brainmass/gallery/model_zoo/hopf.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
|
+
# # Hopf Oscillator
|
|
22
|
+
#
|
|
23
|
+
# The **Hopf (Stuart-Landau normal-form) oscillator** is the canonical model of rhythm onset. Each node obeys the supercritical Hopf normal form
|
|
24
|
+
#
|
|
25
|
+
# $$\dot x = (a - x^2 - y^2)\,x - \omega\,y,\qquad \dot y = (a - x^2 - y^2)\,y + \omega\,x,$$
|
|
26
|
+
#
|
|
27
|
+
# where the bifurcation parameter $a$ controls the regime: for $a<0$ the origin is a stable fixed point (the node is silent), while for $a>0$ a stable limit cycle of radius $\sqrt{a}$ appears and the node oscillates at angular frequency $\omega$. It is the workhorse phenomenological node for whole-brain resting-state models.
|
|
28
|
+
#
|
|
29
|
+
# **Reference:** Deco, Kringelbach, Jirsa & Ritter (2017), *The dynamics of resting fluctuations in the brain*, Scientific Reports 7:3095.
|
|
30
|
+
|
|
31
|
+
# %% [markdown]
|
|
32
|
+
# ## Build the model
|
|
33
|
+
#
|
|
34
|
+
# We pick `a = 0.25 > 0` so the node sits on a limit cycle.
|
|
35
|
+
|
|
36
|
+
# %%
|
|
37
|
+
node = brainmass.HopfStep(in_size=1, a=0.25, w=0.3)
|
|
38
|
+
node
|
|
39
|
+
|
|
40
|
+
# %% [markdown]
|
|
41
|
+
# ## Run a simulation
|
|
42
|
+
#
|
|
43
|
+
# The high-level `Simulator` compiles the whole rollout into one XLA program — no hand-rolled Python loop. We discard a short transient.
|
|
44
|
+
|
|
45
|
+
# %%
|
|
46
|
+
sim = brainmass.Simulator(node, dt=0.1 * u.ms)
|
|
47
|
+
res = sim.run(200. * u.ms, monitors=['x', 'y'], transient=20. * u.ms)
|
|
48
|
+
res['x'].shape, res['ts'][-1]
|
|
49
|
+
|
|
50
|
+
# %% [markdown]
|
|
51
|
+
# ## Visualize
|
|
52
|
+
#
|
|
53
|
+
# The timeseries shows the sustained oscillation; the phase portrait shows the trajectory settling onto the circular limit cycle of radius $\sqrt{a} = 0.5$.
|
|
54
|
+
|
|
55
|
+
# %%
|
|
56
|
+
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
|
|
57
|
+
brainmass.viz.plot_timeseries(res['x'], ts=res['ts'], ax=axes[0])
|
|
58
|
+
axes[0].set_title('Hopf limit cycle (x)')
|
|
59
|
+
brainmass.viz.plot_phase_portrait(res['x'], res['y'], ax=axes[1])
|
|
60
|
+
axes[1].set_title('Phase portrait')
|
|
61
|
+
plt.tight_layout()
|
|
62
|
+
plt.show()
|
|
63
|
+
|
|
64
|
+
# %% [markdown]
|
|
65
|
+
# ## Try it: cross the bifurcation
|
|
66
|
+
#
|
|
67
|
+
# Sweep the bifurcation parameter `a` across zero, giving each node a small kick off the fixed point. For `a <= 0` the node decays back to silence; for `a > 0` the settled amplitude grows as $\sqrt{a}$.
|
|
68
|
+
|
|
69
|
+
# %%
|
|
70
|
+
for a in [-0.2, 0.0, 0.25, 1.0]:
|
|
71
|
+
m = brainmass.HopfStep(in_size=1, a=a, w=0.3)
|
|
72
|
+
brainstate.nn.init_all_states(m)
|
|
73
|
+
m.x.value = m.x.value + 0.1 # small kick off the fixed point
|
|
74
|
+
r = brainmass.Simulator(m, dt=0.1 * u.ms).run(
|
|
75
|
+
300. * u.ms, monitors=['x'], transient=150. * u.ms, init_states=False)
|
|
76
|
+
amp = float(np.sqrt(np.mean(u.get_magnitude(r['x']) ** 2)) * np.sqrt(2))
|
|
77
|
+
print(f'a = {a:+.2f} -> settled amplitude = {amp:.3f} '
|
|
78
|
+
f'(sqrt(a) = {np.sqrt(max(a, 0)):.3f})')
|