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.
Files changed (45) hide show
  1. package/README.md +1 -6
  2. package/manifest.json +3 -2
  3. package/package.json +2 -1
  4. package/skills/braincell/SKILL.md +1 -1
  5. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +107 -44
  6. package/skills/braincell/references/channel-library.md +0 -85
  7. package/skills/braincell/references/ion-library.md +0 -67
  8. package/skills/braincell/references/multicompartment/filter-function-library.md +0 -8
  9. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +204 -65
  10. package/skills/brainmass/SKILL.md +290 -0
  11. package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
  12. package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
  13. package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  14. package/skills/brainmass/references/braintools/cogtask.md +190 -0
  15. package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
  16. package/skills/brainmass/references/braintools/metric.md +157 -0
  17. package/skills/brainmass/references/braintools/optimizer.md +187 -0
  18. package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
  19. package/skills/brainmass/references/braintools/surrogate.md +151 -0
  20. package/skills/brainmass/references/coupling-network-api.md +148 -0
  21. package/skills/brainmass/references/datasets-api.md +72 -0
  22. package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
  23. package/skills/brainmass/references/forward-observation-api.md +131 -0
  24. package/skills/brainmass/references/horn-task-training.md +199 -0
  25. package/skills/brainmass/references/modellibrary.md +104 -0
  26. package/skills/brainmass/references/noiseprocesses.md +121 -0
  27. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
  28. package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
  29. package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
  30. package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
  31. package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
  32. package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
  33. package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
  34. package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
  35. package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
  36. package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
  37. package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
  38. package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
  39. package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
  40. package/skills/brainmass/references/visualization-analysis-api.md +130 -0
  41. package/skills/brainpy-state/SKILL.md +1 -1
  42. package/skills/brainx-general-guard/SKILL.md +52 -118
  43. package/skills/brainx-install/SKILL.md +7 -4
  44. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +0 -303
  45. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +0 -62
@@ -1,121 +1,260 @@
1
1
  # Topology building and visualization
2
2
 
3
- Use this reference after opening `references/multicompartment/multicompartment-cell-workflow.md` when branch topology, control-volume splitting, locset placement, runtime nodes, or spatial values must be inspected rather than inferred.
3
+ Use this reference after `references/multicompartment/multicompartment-cell-workflow.md` when branch topology, CV coverage, runtime nodes, selector placement, or spatial values must be visualized. Keep morphology construction and validation, selector design, CV-policy choice, probe behavior, and simulation in their owning references.
4
4
 
5
- ## Choose the structural view
5
+ ## Choose the view
6
6
 
7
- Morphology branches, CVs, and runtime nodes are different layers of one cell; inspect the layer that owns the suspected error.
7
+ Morphology branches, CVs, and runtime nodes are different layers of one cell; visualize the layer that owns the question.
8
8
 
9
- | API or object | Use when | Important behavior and result |
9
+ | API | Use when | Constraint |
10
10
  |---|---|---|
11
- | `morphology.topo()` | Check imported or manually built parent-child branch structure before discretization. | It renders the named branch tree; it does not show CVs or runtime nodes. |
12
- | `morphology.select(region_or_locset)` | Verify a selector before attaching mechanisms. | A region returns interval data; a locset returns points and `display_names`. |
13
- | `cell.cvs` / `cell.n_cv` | Inspect the membrane-oriented discretization. | The CV preview is resolved lazily from morphology, CV policy, and paint rules and is available before runtime initialization. |
14
- | `cell.init_state()` | Build the execution-oriented runtime. | It transitions the cell from `DECLARING` to `INITIALIZED` and materializes `node_tree`, layouts, State, and probes. |
15
- | `cell.node_tree` | Inspect runtime point and edge connectivity after initialization. | It exposes `nodes`, `edges`, and `root_node_id`; accessing runtime topology while declaring raises `RuntimeError`. |
16
- | `cell.vis_branch(...)` | Inspect compact morphology topology or region coverage. | It draws one node per branch and supports regions only, not locsets or value colormaps. |
17
- | `cell.vis_cv(...)` | Inspect discretization, region coverage, locset ownership, or CV-level values. | It draws one node per CV and supports region, locset, or value mode. |
18
- | `cell.vis_node(...)` | Inspect the full runtime graph, exact lowered placement, or point-level values. | It requires an initialized cell and draws the execution-oriented node tree. |
19
- | `cell.vis_topology(level=...)` | Choose `"branch"`, `"cv"`, or `"node"` dynamically. | It dispatches to the matching visualization method and returns the rendered Matplotlib axes. |
11
+ | `morphology.topo()` | Check the named parent-child branch tree before discretization. | It does not show CVs or runtime nodes. |
12
+ | `morphology.select(expr)` | Confirm region intervals or locset points before plotting. | Use the filter reference when the selection itself is wrong. |
13
+ | `cell.vis_branch(...)` | Inspect compact branch topology or region coverage. | It supports regions, not locsets or values. |
14
+ | `cell.vis_cv(...)` | Inspect discretization, region coverage, locset ownership, or CV values. | Region/locset highlight mode is exclusive with value mode. |
15
+ | `cell.vis_node(...)` | Inspect the full runtime point graph, lowered placement, or point values. | Call `cell.init_state()` first. |
16
+ | `cell.vis_topology(level=...)` | Dispatch dynamically among `"branch"`, `"cv"`, and `"node"`. | Branch level rejects locset and value arguments. |
17
+ | `braincell.vis.plot2d()` / `plot3d()` | Inspect physical morphology geometry. | Use these instead of topology layouts when length, radius, or 3D position matters. |
20
18
 
21
- Do not equate morphology sample points, branches, CVs, and runtime nodes. The morphology defines continuous cable, the CV policy defines isopotential intervals, and `init_state()` lowers those intervals and declarations into the node tree.
19
+ The morphology defines continuous cable, the CV policy defines isopotential intervals, and `init_state()` lowers them into the execution-oriented `NodeTree`. Do not equate morphology points, branches, CVs, and runtime nodes.
22
20
 
23
- ## Build and inspect runtime topology
21
+ ## Prepare the visualization context
24
22
 
25
- Validate selectors against the morphology, inspect CVs before initialization, then inspect the node tree and visual placement after initialization.
23
+ Reuse the validated morphology, selectors, CV policy, and declarations from the multicompartment workflow. This minimal setup exists only to make the visualization snippets executable.
26
24
 
27
25
  ```python
28
26
  import braincell
29
27
  import braincell.mech as mech
30
28
  import brainunit as u
31
29
  import matplotlib.pyplot as plt
32
- from braincell.filter import Terminals, branch_in
30
+ from braincell.filter import AllRegion, RootLocation, Terminals, branch_in
33
31
 
34
32
 
35
33
  morphology = braincell.Morphology.from_swc("neuron.swc")
36
- dendrites = branch_in(
34
+ target_region = branch_in(
37
35
  "type",
38
36
  ("dendrite", "basal_dendrite", "apical_dendrite"),
39
37
  )
40
- terminal_sites = Terminals()
38
+ target_sites = RootLocation(0.5) | Terminals()
41
39
 
42
- print(morphology.topo())
43
- print("dendrite intervals:", morphology.select(dendrites).intervals)
44
- print("terminal points:", morphology.select(terminal_sites).display_names)
40
+ assert morphology.select(target_region).intervals
41
+ assert morphology.select(target_sites).points
45
42
 
46
43
  cell = braincell.Cell(
47
44
  morphology,
48
- cv_policy=braincell.MaxCVLen(20.0 * u.um),
45
+ cv_policy=braincell.MaxCVLen(25.0 * u.um),
49
46
  )
50
- cell.place(terminal_sites, mech.StateProbe())
47
+ cell.paint(
48
+ AllRegion(),
49
+ mech.Channel(
50
+ "IL",
51
+ g_max=0.03 * u.mS / u.cm**2,
52
+ E=-65.0 * u.mV,
53
+ ),
54
+ )
55
+ cell.init_state()
51
56
 
52
57
  assert cell.n_cv == len(cell.cvs)
53
- cell.init_state()
58
+ assert len(cell.node_tree.edges) == len(cell.node_tree.nodes) - 1
59
+ ```
60
+
61
+ Access `cell.node_tree` and node value mode only after `init_state()`. Return to the morphology reference if initialization does not produce one connected rooted tree.
62
+
63
+ ## Compare structure and selector placement
64
+
65
+ Render one selection across structural levels, then show a locset at runtime level. This distinguishes a branch-selection error from CV coverage or point-lowering errors.
66
+
67
+ ```python
68
+ fig, axes = plt.subplots(2, 2, figsize=(10, 9), dpi=140)
54
69
 
55
- print("CVs:", cell.n_cv)
56
- print("runtime nodes:", len(cell.node_tree.nodes))
57
- print("runtime edges:", len(cell.node_tree.edges))
58
- print("root node:", cell.node_tree.root_node_id)
70
+ cell.vis_branch(
71
+ region=target_region,
72
+ coverage_mode="fraction",
73
+ layout="dot",
74
+ ax=axes[0, 0],
75
+ show=False,
76
+ )
77
+ axes[0, 0].set_title("Branch region")
59
78
 
60
- fig, axes = plt.subplots(1, 3, figsize=(12, 4))
61
- cell.vis_branch(region=dendrites, ax=axes[0], show=False)
62
79
  cell.vis_cv(
63
- region=dendrites,
80
+ region=target_region,
64
81
  coverage_mode="fraction",
82
+ layout="dot",
83
+ ax=axes[0, 1],
84
+ show=False,
85
+ )
86
+ axes[0, 1].set_title(f"CV region: n={cell.n_cv}")
87
+
88
+ cell.vis_node(
89
+ region=target_region,
90
+ coverage_mode="fraction",
91
+ layout="dot",
92
+ ax=axes[1, 0],
93
+ show=False,
94
+ )
95
+ axes[1, 0].set_title("Runtime region")
96
+
97
+ cell.vis_node(
98
+ locset=target_sites,
99
+ highlight_color="#f97316",
100
+ layout="dot",
101
+ ax=axes[1, 1],
102
+ show=False,
103
+ )
104
+ axes[1, 1].set_title("Runtime locset")
105
+
106
+ fig.tight_layout()
107
+ plt.show()
108
+ ```
109
+
110
+ Use `coverage_mode="fraction"` to blend by overlap, `"any"` to fully highlight any overlap, and `"all"` to highlight only complete coverage. Node-level regions and locsets map to owning CV midpoint points; they do not render literal morphology coordinates.
111
+
112
+ ## Compare layouts
113
+
114
+ Hold the initialized cell and data fixed while choosing the layout that makes topology easiest to inspect.
115
+
116
+ ```python
117
+ fig, axes = plt.subplots(1, 3, figsize=(13, 4), dpi=140)
118
+
119
+ cell.vis_node(
120
+ preset="dendrotweaks",
121
+ ax=axes[0],
122
+ show=False,
123
+ )
124
+ axes[0].set_title("dendrotweaks")
125
+
126
+ cell.vis_node(
127
+ layout="dot",
65
128
  ax=axes[1],
66
129
  show=False,
67
130
  )
68
- cell.vis_node(locset=terminal_sites, ax=axes[2], show=False)
69
- plt.tight_layout()
131
+ axes[1].set_title("dot")
132
+
133
+ cell.vis_node(
134
+ layout="kamada_kawai",
135
+ layout_scale=1.5,
136
+ ax=axes[2],
137
+ show=False,
138
+ )
139
+ axes[2].set_title("kamada_kawai")
70
140
 
71
- fig, ax = plt.subplots()
72
- cell.vis_node(value="V", cmap="viridis", ax=ax, show=False)
141
+ fig.tight_layout()
73
142
  plt.show()
74
143
  ```
75
144
 
76
- Use selection inspection to verify semantic targeting and visualization to verify the lowering. A correct branch label can still produce an unsuitable CV layout, and a correct CV layout can still expose a wrong locset or mechanism placement.
145
+ Available presets are `"dendrotweaks"`, `"mono"`, and `"depth"`; documented layouts are `"twopi"`, `"dot"`, `"neato"`, and `"kamada_kawai"`. `layout_scale` changes global spacing without changing topology.
77
146
 
78
- ## Select a visualization level
147
+ The default topology preset ignores physical length and radius. Do not interpret graph spacing as cable distance; route physical geometry inspection to the morphology reference.
79
148
 
80
- | Level | Region highlight | Locset highlight | Value color | Best use |
81
- |---|---|---|---|---|
82
- | `"branch"` | Yes | No | No | Compact branch topology and whole-branch or partial-region coverage. |
83
- | `"cv"` | Yes | Yes | Yes | Spatial discretization, owning-CV placement, and compartment-level values. |
84
- | `"node"` | Yes | Yes | Yes | Full runtime topology, lowered point placement, and point-level State or parameters. |
149
+ ## Color runtime and mechanism values
85
150
 
86
- Use `coverage_mode="fraction"` to blend by overlap fraction, `"any"` to fully highlight any overlap, and `"all"` to highlight only complete coverage. These modes apply to region coverage; locset hits are full-intensity point selections.
151
+ Use value mode on an initialized or already simulated cell. Named selectors avoid manually extracting and aligning runtime arrays.
87
152
 
88
- ## Highlight targets or color values
153
+ ```python
154
+ fig, axes = plt.subplots(1, 2, figsize=(10, 4), dpi=140)
89
155
 
90
- Highlight mode verifies where a declaration resolves. Value mode displays runtime or user-supplied scalar data.
156
+ cell.vis_node(
157
+ value="V",
158
+ cmap="viridis",
159
+ vmin=-80.0,
160
+ vmax=-40.0,
161
+ value_label="Voltage",
162
+ ax=axes[0],
163
+ show=False,
164
+ )
165
+ axes[0].set_title("Membrane voltage")
91
166
 
92
- | `value` form | Result |
93
- |---|---|
94
- | Point-space array of length `n_point` | Color runtime nodes directly. |
95
- | CV-space array of length `n_cv` | Scatter each CV value into point space. |
96
- | `"V"` or `"voltage"` | Color by membrane voltage. |
97
- | `("ion", ion_name, field)` | Color by one ion runtime field. |
98
- | `("channel", class_name, field)` | Color by one channel field, such as `("channel", "IL", "g_max")`. |
99
- | `("layout_id", layout_id, field)` | Color by one resolved runtime layout field. |
167
+ cell.vis_node(
168
+ value=("channel", "IL", "g_max"),
169
+ cmap="magma",
170
+ value_label="IL g_max",
171
+ ax=axes[1],
172
+ show=False,
173
+ )
174
+ axes[1].set_title("Leak conductance")
175
+
176
+ fig.tight_layout()
177
+ plt.show()
178
+ ```
179
+
180
+ Keep `vmin`, `vmax`, and `cmap` fixed when comparing cells or time points. Run the cell through the parent workflow first when the figure must show post-stimulus rather than initialized State.
181
+
182
+ ## Color a custom node metric
183
+
184
+ Pass one scalar per runtime point when the built-in value selectors do not own the diagnostic quantity. This example maps graph depth from the runtime root.
185
+
186
+ ```python
187
+ from collections import deque
188
+
189
+ import numpy as np
100
190
 
101
- Do not combine `value` with `region` or `locset`; highlight mode and value mode are mutually exclusive. At node level, regions and locsets map to the midpoint point of the owning CV, so a highlight is a runtime-placement view rather than a literal rendering of every morphology coordinate.
102
191
 
103
- ## Control layout and rendering
192
+ def node_depths(tree):
193
+ depths = np.full(len(tree.nodes), np.nan)
194
+ depths[tree.root_node_id] = 0.0
195
+ children = {node.id: [] for node in tree.nodes}
196
+
197
+ for edge in tree.edges:
198
+ children[edge.parent_node_id].append(edge.child_node_id)
199
+
200
+ queue = deque([tree.root_node_id])
201
+ while queue:
202
+ parent = queue.popleft()
203
+ for child in children[parent]:
204
+ depths[child] = depths[parent] + 1.0
205
+ queue.append(child)
206
+
207
+ return depths
208
+
209
+
210
+ depth = node_depths(cell.node_tree)
211
+ assert depth.shape == (len(cell.node_tree.nodes),)
212
+ assert not np.isnan(depth).any()
213
+
214
+ fig, ax = plt.subplots(figsize=(7, 7), dpi=140)
215
+ cell.vis_node(
216
+ value=depth,
217
+ cmap="magma",
218
+ value_label="Runtime graph depth",
219
+ ax=ax,
220
+ show=False,
221
+ )
222
+ fig.tight_layout()
223
+ plt.show()
224
+ ```
225
+
226
+ A point-space array must have length `n_point`. A CV-space array must have length `n_cv`; `vis_node()` scatters it into point space. Other shapes raise `ValueError`.
227
+
228
+ ## Lookup
229
+
230
+ | Level | Region | Locset | Value | Best use |
231
+ |---|---|---|---|---|
232
+ | `"branch"` | Yes | No | No | Compact branch topology and region coverage. |
233
+ | `"cv"` | Yes | Yes | Yes | Discretization, owning-CV placement, and compartment values. |
234
+ | `"node"` | Yes | Yes | Yes | Full runtime topology, lowered placement, and point values. |
235
+
236
+ | `value` form | Result |
237
+ |---|---|
238
+ | Point array of length `n_point` | Color runtime nodes directly. |
239
+ | CV array of length `n_cv` | Scatter CV values into point space. |
240
+ | `"V"` or `"voltage"` | Color membrane voltage. |
241
+ | `("ion", ion_name, field)` | Color one ion field. |
242
+ | `("channel", class_name, field)` | Color one channel field. |
243
+ | `("layout_id", layout_id, field)` | Color one resolved layout field. |
104
244
 
105
- | Parameter | Use |
245
+ | Control | Use |
106
246
  |---|---|
107
- | `preset="dendrotweaks"`, `"mono"`, or `"depth"` | Choose a documented topology styling preset. |
108
- | `layout="twopi"`, `"dot"`, `"neato"`, or `"kamada_kawai"` | Override the graph layout algorithm. |
109
- | `layout_scale=float` | Tighten values below `1.0` or spread values above `1.0`. |
110
- | `highlight_color=...` | Set the selection overlay color. |
111
- | `cmap`, `vmin`, `vmax`, `norm`, `value_label`, `show_colorbar` | Control value-mode normalization and labeling. |
112
- | `node_color`, `edge_color`, `root_color` | Override low-level topology colors. |
113
- | `ax=...`, `show=False` | Render into an existing Matplotlib axes without calling `plt.show()`. |
247
+ | `highlight_color` / `coverage_mode` | Style region or locset highlights. |
248
+ | `cmap`, `vmin`, `vmax`, `norm` | Control value normalization. |
249
+ | `value_label`, `show_colorbar` | Control the colorbar. |
250
+ | `node_color`, `edge_color`, `root_color` | Style topology without entering value mode. |
251
+ | `ax=...`, `show=False` | Compose subplots; call `plt.show()` or `fig.savefig(...)` once afterward. |
114
252
 
115
- For debugging, keep the selector and CV policy fixed while changing visualization levels. Keep the visualization level fixed while comparing CV policies. This isolates whether the mismatch comes from branch selection, discretization, or runtime lowering.
253
+ Highlight mode and value mode are mutually exclusive. Fix selectors in `filter-function-library.md`, discretization in `cv-policy-reference.md`, morphology geometry in the IO or manual-construction reference, and recorded-trace mismatches in `probe-reference.md`.
116
254
 
117
255
  ## Sources
118
256
 
119
257
  - [Point tree visualization](https://brainx.chaobrain.com/braincell/tutorials/vis.html)
120
258
  - [Region and locset filters](https://brainx.chaobrain.com/braincell/tutorials/filter.html)
259
+ - [Morphology](https://brainx.chaobrain.com/braincell/concepts/morphology.html)
121
260
  - [Cell API](https://brainx.chaobrain.com/braincell/apis/generated/braincell.Cell.html)
@@ -0,0 +1,290 @@
1
+ ---
2
+ name: brainmass
3
+ description: Use for neural-mass modeling of aggregate population activity at the local-circuit, brain-region, multi-region, or whole-brain scale. Use alone for mass-model studies or together with BrainPy-State and/or BrainCell when aggregate dynamics participate in a multiscale model.
4
+ ---
5
+
6
+ # BrainMass
7
+
8
+ ## Purpose and boundary
9
+
10
+ Use BrainMass to translate a regional or whole-brain modeling question into:
11
+
12
+ `select a model -> construct a *Step -> add noise or coupling -> simulate -> observe -> validate or fit`
13
+
14
+ ## Underlying principle of BrainMass
15
+
16
+ A neural-mass model represents the average activity of a neuronal population. It defines population-level state variables and differential equations that govern how they evolve over time.
17
+
18
+ A `*Step` implementation represents the executable one-step dynamics of that model for one or more brain regions. It stores the dynamical variables and advances their differential equations by one integration step.
19
+
20
+ A noise process represents unresolved fluctuations or stochastic drive. It is attached to a model variable and sampled inside the model update.
21
+
22
+ `Network` represents whole-brain wiring. It maps structural connectivity, transmission distance, speed, and a coupling rule into delayed inter-region input.
23
+
24
+ ### API structure
25
+
26
+ | API family | Use |
27
+ |---|---|
28
+ | Neural Mass Models | Choose regional phenomenological, physiological, seizure, decision, oscillator, or whole-brain dynamics. |
29
+ | Noise Processes | Add Gaussian, white, Ornstein-Uhlenbeck, Brownian, or colored stochastic drive to model variables. |
30
+ | Coupling Mechanisms | Choose how structural connections transform regional activity into instantaneous or delayed network input. |
31
+ | Forward Models | Map latent neural activity to modality-specific BOLD, EEG, MEG, or lead-field outputs. |
32
+ | Observation Models | Apply HRF kernels, hemodynamic BOLD dynamics, or temporal averaging to simulated activity. |
33
+ | HORN Models | Build harmonic-oscillator recurrent networks for cognitive and sequence tasks. |
34
+ | Orchestration | Run and fit models through `Network`, `Simulator`, `Fitter`, `FitResult`, and objective functions. |
35
+ | Datasets | Load or register connectomes, signals, and task datasets through typed data containers. |
36
+ | Visualization | Plot trajectories, phase portraits, connectivity, functional connectivity, and spectra. |
37
+ | Utilities & Types | Discover models, inspect `ModelInfo`, compute delay indices, and use shared helpers. |
38
+
39
+ ## Discover and simulate a model
40
+
41
+ Every public regional model follows the same `*Step` contract, so choose by scientific observable and dynamical regime, then let `Simulator` own initialization and the transformed time loop.
42
+
43
+ | API | Description |
44
+ |---|---|
45
+ | `brainmass.list_models()` | Use before choosing a model; it returns `ModelInfo` records with name, category, state-variable count, and use case. |
46
+ | `brainmass.<Model>Step(in_size, **params)` | Use after selecting a model family; `in_size` sets the number of regions or parallel units and parameters broadcast to that shape. |
47
+ | `brainmass.Simulator(model, dt=...)` | Use for the default, standard run path; it stores the model and integration step without changing the model equations. |
48
+ | `Simulator.run(duration, ..., monitors=..., transient=...)` | Use to initialize State, execute the compiled loop, discard a warm-up interval, and return a dict of time-major trajectories plus unit-aware `ts`. |
49
+
50
+ ```python
51
+ import brainmass
52
+ import brainunit as u
53
+
54
+ models = brainmass.list_models()
55
+ hopf = next(model for model in models if model.name == "HopfStep")
56
+ assert hopf.category == "phenomenological"
57
+
58
+ node = brainmass.HopfStep(in_size=1, a=0.25, w=0.3)
59
+ result = brainmass.Simulator(node, dt=0.1 * u.ms).run(
60
+ 200.0 * u.ms,
61
+ monitors=["x", "y"],
62
+ transient=20.0 * u.ms,
63
+ )
64
+
65
+ assert set(result) == {"x", "y", "ts"}
66
+ assert result["x"].shape == (1800, 1)
67
+ assert result["ts"].shape == (1800,)
68
+ ```
69
+
70
+ Open `references/modellibrary.md` when choosing among model families, distinguishing similarly named Wong-Wang variants, comparing state cost, or locating a model's observable. Open `references/datasets-api.md` when the workflow needs bundled or registered input data.
71
+
72
+ ## Noise and stochastic run
73
+
74
+ Noise belongs to the model, while `batch_size` asks `Simulator` to initialize and run independent State realizations in one time-major result.
75
+
76
+ | API | Description |
77
+ |---|---|
78
+ | `brainmass.OUProcess(in_size, sigma=..., tau=...)` | Use for mean-reverting temporally correlated drive; `sigma` sets output scale and `tau` sets correlation time. |
79
+ | `brainstate.random.seed(seed)` | Use before constructing or running every stochastic result that must be reproducible; it resets the BrainState random stream. |
80
+ | `Simulator.run(..., batch_size=N)` | Use for `N` independent trials; it initializes batched model and noise State and returns trajectories shaped `(time, batch, regions)`. |
81
+
82
+ ```python
83
+ import brainmass
84
+ import brainstate
85
+ import brainunit as u
86
+
87
+ brainstate.random.seed(7)
88
+ node = brainmass.HopfStep(
89
+ in_size=1,
90
+ a=-0.05,
91
+ w=0.3,
92
+ noise_x=brainmass.OUProcess(
93
+ in_size=1,
94
+ sigma=0.1,
95
+ tau=20.0 * u.ms,
96
+ ),
97
+ )
98
+ trials = brainmass.Simulator(node, dt=0.1 * u.ms).run(
99
+ 100.0 * u.ms,
100
+ monitors=["x"],
101
+ batch_size=8,
102
+ )
103
+
104
+ assert trials["x"].shape == (1000, 8, 1)
105
+ ```
106
+
107
+ Seed again before a repeated run when exact replay matters.
108
+
109
+ Open `references/noiseprocesses.md` when choosing white, OU, Brownian, or colored noise, using a noise process directly, or checking units and State behavior. Open `references/batch-transform-acceleration.md` when batching parameters, writing a custom transformed loop, or checkpointing a long differentiated rollout.
110
+
111
+ ## Build a delay-coupled network
112
+
113
+ `Network` wraps an `N`-region `*Step` model with structural connectivity, optional conduction delays, and one coupling current while preserving the `Simulator` contract.
114
+
115
+ | API | Description |
116
+ |---|---|
117
+ | `brainstate.environ.set(dt=...)` | Use to establish the persistent integration step from which a delay-coupled `Network` sizes its history buffer. |
118
+ | `brainmass.datasets.load_dataset("example_connectome")` | Use for the bundled typed `Connectome`; it returns weights, unit-aware distances, and region labels. |
119
+ | `brainmass.Network(node, conn=..., distance=..., speed=..., coupling=..., coupled_var=..., k=...)` | Use to couple an `N`-region node bank; it derives `distance / speed` delays, validates the coupled State, and returns a Module driven like the original node. |
120
+ | `Simulator.run(..., monitors=lambda m: m.node.<state>.value)` | Use to record coupled node State; a callable traverses the `Network.node` boundary and stores the result under `"output"`. |
121
+
122
+ ```python
123
+ import brainmass
124
+ import brainstate
125
+ import brainunit as u
126
+
127
+ dt = 0.1 * u.ms
128
+ brainstate.environ.set(dt=dt)
129
+
130
+ connectome = brainmass.datasets.load_dataset("example_connectome")
131
+ n_region = connectome.weights.shape[0]
132
+ nodes = brainmass.HopfStep(in_size=n_region, a=0.2, w=0.3)
133
+ network = brainmass.Network(
134
+ nodes,
135
+ conn=connectome.weights,
136
+ distance=connectome.distances,
137
+ speed=10.0 * u.mm / u.ms,
138
+ coupling="diffusive",
139
+ coupled_var="x",
140
+ k=0.5,
141
+ )
142
+ result = brainmass.Simulator(network, dt=dt).run(
143
+ 200.0 * u.ms,
144
+ monitors=lambda model: model.node.x.value,
145
+ transient=20.0 * u.ms,
146
+ )
147
+
148
+ assert result["output"].shape == (1800, n_region)
149
+ ```
150
+
151
+
152
+ Open `references/coupling-network-api.md` when selecting diffusive, additive, Laplacian, sigmoidal, tanh, or Jansen-Rit coupling; configuring instantaneous coupling; fitting coupling parameters; or building a direct coupling object.
153
+
154
+ ## Map activity to observables
155
+
156
+ An observation model converts hidden activity to the modality actually measured, so choose its temporal and physical assumptions before defining the comparison target.
157
+
158
+ | API | Description |
159
+ |---|---|
160
+ | `brainmass.HRFBold(period=..., downsample_period=..., kernel=...)` | Use for fast differentiable BOLD fitting; it temporally averages, convolves with an HRF kernel, and decimates to the requested repetition time. |
161
+ | `brainmass.BOLDSignal(in_size=...)` | Use when four-state Balloon-Windkessel hemodynamics matter more than the simpler convolution path. |
162
+ | `brainmass.EEGLeadFieldModel(...)` | Use with a physically calibrated EEG lead field; it projects regional sources to sensor potentials while preserving units. |
163
+ | `brainmass.LeadFieldModel(...)` | Use for a generic physical lead-field projection with explicit dipole and sensor units. |
164
+ | `brainmass.MEGLeadFieldModel(...)` | Use for the MEG specialization; match lead-field, dipole, and magnetic-field units. |
165
+ | `brainmass.LeadfieldReadout(...)` | Use when a unitless lead-field matrix should be learned end to end rather than supplied as a calibrated physical operator. |
166
+
167
+ ```python
168
+ import brainmass
169
+ import brainunit as u
170
+
171
+ node = brainmass.WilsonCowanStep(in_size=1)
172
+ neural = brainmass.Simulator(node, dt=1.0 * u.ms).run(
173
+ 6000.0 * u.ms,
174
+ monitors=["rE"],
175
+ transient=500.0 * u.ms,
176
+ )["rE"]
177
+
178
+ observer = brainmass.HRFBold(
179
+ period=720.0 * u.ms,
180
+ downsample_period=20.0 * u.ms,
181
+ kernel=brainmass.GammaHRFKernel(),
182
+ )
183
+ bold = observer(u.get_magnitude(neural), dt=1.0 * u.ms)
184
+
185
+ assert bold.ndim == 2
186
+ assert bold.shape[1] == 1
187
+ ```
188
+
189
+ Strip units only at an explicitly documented raw-array boundary. Use `HRFBold` for the canonical differentiable BOLD path.
190
+
191
+ Open `references/forward-observation-api.md` when choosing an HRF kernel, Balloon-Windkessel BOLD, temporal averaging, EEG/MEG lead fields, a trainable readout, or modality-specific unit handling.
192
+
193
+ ## Fit trainable parameters
194
+
195
+ `Fitter` discovers `Param(fit=True)` values, evaluates one scalar objective through the model workflow, and returns the best constrained parameters without changing the scientific simulation path.
196
+
197
+ | API | Description |
198
+ |---|---|
199
+ | `brainstate.nn.Param(value, ..., fit=True)` | Use to mark exactly the model parameters that may change; an optional transform constrains their physical values. |
200
+ | `brainmass.objectives.<builder>()` | Use with `predict=` for reusable time-series, FC, FCD, cosine, or combined objectives; each builder returns a scalar callable. |
201
+ | `brainmass.Fitter(model, optimizer, loss_fn=..., backend="grad")` | Use for a custom `loss_fn(model) -> (scalar_loss, aux)`; the default gradient backend differentiates through the simulation and optimizer steps. |
202
+ | `brainmass.Fitter(model, optimizer, predict=..., objective=...)` | Use when a trajectory prediction is compared directly with a target by a reusable objective. |
203
+ | `Fitter.fit(target=None, n_steps=...)` | Use to run backend-specific iterations and return `FitResult` with best loss, parameters, history, prediction, and fitted model. |
204
+
205
+ ```python
206
+ import brainmass
207
+ import brainunit as u
208
+ import braintools
209
+ import jax.numpy as jnp
210
+ import numpy as np
211
+ from brainstate.nn import Param
212
+
213
+ signal = brainmass.datasets.load_dataset("example_signal").signal[:, 0]
214
+ target_amp = jnp.asarray(
215
+ float(np.sqrt(np.mean((signal - signal.mean()) ** 2)))
216
+ )
217
+
218
+ model = brainmass.HopfStep(
219
+ in_size=1,
220
+ a=Param(0.05, fit=True),
221
+ w=0.3,
222
+ beta=1.0,
223
+ init_x=braintools.init.Constant(0.5),
224
+ )
225
+
226
+ def loss_fn(candidate):
227
+ x = brainmass.Simulator(candidate, dt=0.1 * u.ms).run(
228
+ 300.0 * u.ms,
229
+ monitors=["x"],
230
+ transient=150.0 * u.ms,
231
+ )["x"][:, 0]
232
+ amplitude = jnp.sqrt(jnp.mean((x - jnp.mean(x)) ** 2))
233
+ return (amplitude - target_amp) ** 2, amplitude
234
+
235
+ fitter = brainmass.Fitter(
236
+ model,
237
+ braintools.optim.Adam(lr=0.05),
238
+ loss_fn=loss_fn,
239
+ )
240
+ fit = fitter.fit(n_steps=50)
241
+
242
+ assert fit.best_loss <= fit.history[0]
243
+ assert "a" in fit.best_params
244
+ ```
245
+
246
+ Fit phase-insensitive summaries such as amplitude, spectrum, FC, or FCD when raw oscillatory traces can differ only by phase. Use `backend="grad"` whenever the workflow is differentiable.
247
+
248
+ Open `references/fitting-with-objectives-api.md` when choosing `loss_fn` versus `predict` plus `objective`, selecting built-in objectives, configuring callbacks, interpreting `FitResult`, or changing backends. Open `references/brainstate/parameter-constraints-regularization.md` when a fitted parameter needs a valid-domain transform, penalty, or prior. Open `references/braintools/optimizer.md` when choosing an optimizer or learning-rate scheduler beyond the canonical `Adam` path. Open `references/scripts/gradient-free-fitting.py` only when the objective is discrete, jagged, black-box, or has unavailable or unreliable gradients; its bounded search-space workflow is required.
249
+
250
+ ## Reference routing
251
+
252
+ Choose the workflow category first, then open only the smallest reference that owns the next decision.
253
+
254
+ ### Modeling, simulation, and analysis
255
+
256
+ | Reference | Open when |
257
+ |---|---|
258
+ | `references/modellibrary.md` | Choosing a model family, observable, state cost, or similarly named variant. |
259
+ | `references/noiseprocesses.md` | Selecting a noise spectrum, correlation structure, State behavior, units, or direct noise workflow. |
260
+ | `references/datasets-api.md` | Loading, inspecting, generating, or registering BrainMass data containers. |
261
+ | `references/coupling-network-api.md` | Selecting or configuring coupling, delays, connectivity conventions, direct coupling objects, or trainable network parameters. |
262
+ | `references/forward-observation-api.md` | Selecting BOLD, HRF kernels, temporal averaging, EEG/MEG lead fields, or trainable readouts. |
263
+ | `references/visualization-analysis-api.md` | Plotting or computing time-series, FC, FCD, and spectral summaries. |
264
+
265
+ ### Fitting and regime exploration
266
+
267
+ | Reference | Open when |
268
+ |---|---|
269
+ | `references/fitting-with-objectives-api.md` | Selecting a fitter interface, objective, backend, search space, callback, or result field. |
270
+ | `references/parameter-sweeps-and-regime-analysis.md` | Mapping regimes or sensitivities over parameter grids instead of fitting one target. |
271
+
272
+ ### HORN task training
273
+
274
+ | Reference | Open when |
275
+ |---|---|
276
+ | `references/horn-task-training.md` | Training HORN networks on minibatched sequence tasks with held-out metrics. |
277
+ | `references/braintools/cogtask.md` | Generating phase-structured cognitive trials for direct HORN task training. |
278
+
279
+ ### Shared data, execution, and optimization support
280
+
281
+ | Reference | Open when |
282
+ |---|---|
283
+ | `references/braintools/data-preprocessing.md` | Encoding custom experimental or task inputs before training; ordinary HORN features do not require it. |
284
+ | `references/batch-transform-acceleration.md` | Writing custom transformed execution, batching parameters, timing JAX, or checkpointing long gradients. |
285
+ | `references/brainstate/parameter-constraints-regularization.md` | Constraining or regularizing fitted parameters and directly trained HORN parameters. |
286
+ | `references/brainstate/parameter-transforms-regularizers-catalog.md` | Selecting an exact transform or regularizer after the parameter workflow reference routes here. |
287
+ | `references/braintools/metric.md` | Selecting supervised HORN losses, held-out metrics, or custom fitting statistics outside `brainmass.objectives`. |
288
+ | `references/braintools/optimizer.md` | Selecting gradient optimizers, schedules, standalone search wrappers, and their update lifecycle. |
289
+ | `references/braintools/parameter-initializer.md` | Initializing model State, fitted starting values, HORN weights, or distance-modulated parameters. |
290
+ | `references/braintools/surrogate.md` | Training a custom path with hard thresholds or spikes; canonical BrainMass and HORN workflows do not need surrogates. |