brainx-skill 1.0.14 → 1.0.16
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 +17 -1
- package/manifest.json +1 -1
- package/mcp-servers/codex/skills.json +1 -1
- package/package.json +1 -1
- package/skills/bio-neuro-lit/SKILL.md +4 -2
- package/skills/bio-neuro-lit/references/required-supplements.md +27 -0
- package/skills/brainx-acceleration/SKILL.md +30 -437
- package/skills/brainx-acceleration/references/audit-and-rewrite-patterns.md +326 -0
- package/skills/brainx-general-guard/SKILL.md +24 -8
- package/skills/brainx-install/SKILL.md +3 -3
- package/skills/brainx-install/references/compatibility-and-release-matching.md +28 -20
- package/skills/brainx-install/references/uninstall-and-cleanup.md +11 -4
- package/skills/brainx-modeling-loop/SKILL.md +143 -36
- package/skills/brainx-modeling-loop/agents/openai.yaml +2 -2
- package/skills/brainx-modeling-loop/references/mechanism-comparison.md +62 -0
- package/skills/brainx-modeling-loop/references/multiscale-coupling.md +16 -0
- package/skills/brainx-modeling-loop/references/paper-reproduction.md +42 -0
- package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +14 -14
- package/skills/brainx-modeling-loop/references/run-experiment.md +1 -1
- package/skills/brainx-modeling-loop/references/training-workflow.md +10 -8
- package/skills/brainx-visualization/SKILL.md +6 -2
- package/skills/brainx-visualization/references/neural-data-visualization.md +1 -1
- package/skills/brainx-visualization/references/statistical-and-model-visualization.md +1 -1
- package/skills/package-skills/braincell/SKILL.md +23 -14
- package/skills/package-skills/braincell/references/braintools/input-current.md +1 -1
- package/skills/package-skills/braincell/references/braintools/metric.md +72 -46
- package/skills/package-skills/braincell/references/mixions-for-adaptation.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/cv-policy-reference.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/filter-function-library.md +3 -3
- package/skills/package-skills/braincell/references/multicompartment/morphology-io-loading-validation.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +31 -43
- package/skills/package-skills/braincell/references/multicompartment/network-workflow.md +49 -0
- package/skills/package-skills/braincell/references/multicompartment/probe-reference.md +26 -114
- package/skills/package-skills/braincell/references/multicompartment/topology-building-and-visualization.md +40 -28
- package/skills/package-skills/braincell/references/scripts/cell_multicompartment_reference.py +13 -17
- package/skills/package-skills/brainevent/SKILL.md +0 -3
- package/skills/package-skills/brainevent/references/synaptic-plasticity.md +1 -1
- package/skills/package-skills/brainmass/SKILL.md +5 -3
- package/skills/package-skills/brainmass/references/brainstate/parameter-constraints-regularization.md +9 -7
- package/skills/package-skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
- package/skills/package-skills/brainmass/references/braintools/data-preprocessing.md +15 -7
- package/skills/package-skills/brainmass/references/braintools/metric.md +72 -46
- package/skills/package-skills/brainmass/references/coupling-network-api.md +3 -1
- package/skills/package-skills/brainmass/references/fitting-with-objectives-api.md +6 -6
- package/skills/package-skills/brainmass/references/horn-task-training.md +9 -9
- package/skills/package-skills/brainmass/references/modellibrary.md +12 -10
- package/skills/package-skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +5 -3
- package/skills/package-skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +10 -6
- package/skills/package-skills/brainmass/references/simulator-input-monitor-api.md +3 -1
- package/skills/package-skills/brainmass/references/visualization-analysis-api.md +17 -9
- package/skills/package-skills/brainspike/SKILL.md +201 -0
- package/skills/package-skills/brainspike/references/braintools/connectivity.md +40 -0
- package/skills/package-skills/brainspike/references/braintools/data-preprocessing.md +39 -0
- package/skills/package-skills/brainspike/references/braintools/input-current.md +55 -0
- package/skills/package-skills/brainspike/references/braintools/metric.md +36 -0
- package/skills/package-skills/brainspike/references/braintools/optimizer.md +50 -0
- package/skills/package-skills/brainspike/references/braintools/parameter-initializer.md +43 -0
- package/skills/package-skills/brainspike/references/braintools/surrogate.md +40 -0
- package/skills/package-skills/brainspike/references/migration-boundary.md +38 -0
- package/skills/package-skills/brainspike/references/model-and-readout-selection.md +41 -0
- package/skills/package-skills/brainspike/references/multirate-coupling.md +31 -0
- package/skills/package-skills/brainspike/references/multiscale-composition.md +28 -0
- package/skills/package-skills/brainspike/references/native-composition.md +52 -0
- package/skills/package-skills/brainspike/references/native-delays.md +34 -0
- package/skills/package-skills/brainspike/references/native-projections.md +43 -0
- package/skills/package-skills/brainspike/references/native-training.md +36 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/devices.md +33 -33
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/divergence-and-parity.md +15 -15
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/integration-categories.md +1 -1
- package/skills/package-skills/brainspike/references/nest-compatible/model-library.md +200 -0
- package/skills/package-skills/brainspike/references/nest-compatible/network-building.md +276 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brette_et_al_2007.py +23 -26
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_alpha.py +18 -21
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_delta.py +16 -19
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +11 -12
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +10 -11
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/spatial_gaussex.py +18 -18
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/synapsecollection.py +26 -29
- package/skills/package-skills/brainspike/references/nest-compatible/synapse-and-connectivity.md +166 -0
- package/skills/package-skills/brainspike/references/nest-delay-boundaries.md +31 -0
- package/skills/package-skills/brainspike/references/nonlinear-state-sharing.md +26 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/perturbation-experiment-validity.md +2 -2
- package/skills/package-skills/brainspike/references/simulator-training.md +61 -0
- package/skills/package-skills/brainspike/references/temporal-task-training.md +36 -0
- package/skills/package-skills/brainspike/scripts/advanced_native_patterns.py +76 -0
- package/skills/package-skills/brainspike/scripts/delay_workflow.py +44 -0
- package/skills/package-skills/brainspike/scripts/delayed_cue_training.py +78 -0
- package/skills/package-skills/brainspike/scripts/lif_smoke.py +31 -0
- package/skills/package-skills/brainspike/scripts/multiscale_workflow.py +35 -0
- package/skills/package-skills/brainspike/scripts/native_ei_network.py +47 -0
- package/skills/package-skills/brainspike/scripts/native_workflows.py +77 -0
- package/skills/package-skills/brainspike/scripts/nest_boundary_workflows.py +108 -0
- package/skills/package-skills/brainspike/scripts/train_native_snn.py +65 -0
- package/skills/package-skills/brainspike/scripts/train_nest_simulator.py +69 -0
- package/skills/package-skills/brainspike/scripts/train_nest_simulator_two_weights.py +220 -0
- package/skills/package-skills/brainstate/SKILL.md +16 -21
- package/skills/package-skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +1 -138
- package/skills/package-skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
- package/skills/package-skills/brainstate/references/brainstate/delay-buffers.md +45 -0
- package/skills/package-skills/brainstate/references/brainstate/parameter-constraints-regularization.md +9 -7
- package/skills/package-skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
- package/skills/package-skills/brainstate/references/brainstate/randomness-and-reproducibility.md +6 -4
- package/skills/package-skills/brainstate/references/brainstate/transformation-grad-expansion.md +4 -4
- package/skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md +1 -1
- package/skills/package-skills/brainstate/references/braintools-optimizer-reference.md +16 -0
- package/skills/package-skills/brainstate/references/libraries/prebuilt-layer-library.md +1 -1
- package/skills/package-skills/brainstate/references/simulation-environment.md +5 -5
- package/skills/package-skills/braintrace/SKILL.md +17 -38
- package/skills/package-skills/braintrace/references/Drtrl.md +9 -26
- package/skills/package-skills/braintrace/references/algorithm selection.md +7 -12
- package/skills/package-skills/braintrace/references/batching.md +15 -35
- package/skills/package-skills/braintrace/references/compiler_internal.md +1 -1
- package/skills/package-skills/braintrace/references/custom algorithms.md +1 -2
- package/skills/package-skills/braintrace/references/customizing_primitive_transforms.md +26 -15
- package/skills/package-skills/braintrace/references/pp_pprop workflow.md +5 -139
- package/skills/package-skills/brainunit/SKILL.md +7 -2
- package/skills/package-skills/brainunit/references/array-mechanics/functional-structural-api.md +1 -1
- package/skills/package-skills/brainunit/references/math-function-library.md +2 -2
- package/skills/package-skills/brainunit/references/typing-and-runtime-validation.md +5 -2
- package/skills/package-skills/brainevent/references/scripts/102_EI_net_1996.py +0 -107
- package/skills/package-skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +0 -168
- package/skills/package-skills/brainevent/references/scripts/coba_ei_teaching.py +0 -356
- package/skills/package-skills/brainpy-state/SKILL.md +0 -247
- package/skills/package-skills/brainpy-state/references/array-creation.md +0 -158
- package/skills/package-skills/brainpy-state/references/brain-dynamics-delay-protocol.md +0 -147
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/analysis.md +0 -150
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +0 -373
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -150
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +0 -175
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +0 -286
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +0 -111
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -163
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -113
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -136
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -222
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -123
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +0 -107
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -185
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/integrators.md +0 -181
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +0 -102
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +0 -147
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +0 -159
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +0 -127
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +0 -167
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +0 -107
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -186
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +0 -104
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +0 -89
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +0 -253
- package/skills/package-skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +0 -334
- package/skills/package-skills/brainpy-state/references/braintools/connectivity.md +0 -206
- package/skills/package-skills/brainpy-state/references/braintools/data-preprocessing.md +0 -79
- package/skills/package-skills/brainpy-state/references/braintools/input-current.md +0 -199
- package/skills/package-skills/brainpy-state/references/braintools/metric.md +0 -152
- package/skills/package-skills/brainpy-state/references/braintools/optimizer.md +0 -179
- package/skills/package-skills/brainpy-state/references/braintools/parameter-initializer.md +0 -183
- package/skills/package-skills/brainpy-state/references/braintools/surrogate.md +0 -147
- package/skills/package-skills/brainpy-state/references/component-selection.md +0 -288
- package/skills/package-skills/brainpy-state/references/nest-compatible/model-library.md +0 -200
- package/skills/package-skills/brainpy-state/references/nest-compatible/nest-workflow.md +0 -156
- package/skills/package-skills/brainpy-state/references/nest-compatible/network-building.md +0 -264
- package/skills/package-skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +0 -153
- package/skills/package-skills/brainpy-state/references/projection-patterns.md +0 -127
- package/skills/package-skills/brainpy-state/references/scripts/103_COBA_2005.py +0 -86
- package/skills/package-skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +0 -181
- package/skills/package-skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +0 -156
- package/skills/package-skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +0 -111
- package/skills/package-skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -221
- package/skills/package-skills/brainpy-state/references/scripts/sound_localization.py +0 -240
- package/skills/package-skills/brainpy-state/references/scripts/training-snn.py +0 -119
package/skills/package-skills/braincell/references/scripts/cell_multicompartment_reference.py
CHANGED
|
@@ -8,6 +8,7 @@ All BrainCell reference scripts live in this directory.
|
|
|
8
8
|
|
|
9
9
|
# 1. Imports and CPU/JAX setup.
|
|
10
10
|
# Set the platform before importing JAX-backed BrainCell/BrainState packages.
|
|
11
|
+
import argparse
|
|
11
12
|
import os
|
|
12
13
|
|
|
13
14
|
os.environ.setdefault("JAX_PLATFORMS", "cpu")
|
|
@@ -20,13 +21,13 @@ import matplotlib.pyplot as plt
|
|
|
20
21
|
from braincell import Cell, Morphology
|
|
21
22
|
from braincell import CVPerBranch, MaxCVLen
|
|
22
23
|
from braincell.filter import BranchSlice, RootLocation, at
|
|
23
|
-
from braincell.mech import CableProperty, Channel, CurrentClamp
|
|
24
|
+
from braincell.mech import CableProperty, Channel, CurrentClamp
|
|
24
25
|
|
|
25
26
|
|
|
26
27
|
# 2. Load morphology from SWC.
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
morpho = Morphology.from_swc(
|
|
28
|
+
parser = argparse.ArgumentParser(description="Run the multicompartment cell example.")
|
|
29
|
+
parser.add_argument("swc", help="Path to an SWC containing a soma and at least one dendrite")
|
|
30
|
+
morpho = Morphology.from_swc(parser.parse_args().swc)
|
|
30
31
|
|
|
31
32
|
print("Morphology topology:")
|
|
32
33
|
print(morpho.topo())
|
|
@@ -142,20 +143,18 @@ channel_cell.paint(
|
|
|
142
143
|
|
|
143
144
|
channel_cell.init_state()
|
|
144
145
|
layout = channel_cell.layouts[0]
|
|
145
|
-
point_id = int(layout.point_index[0])
|
|
146
146
|
|
|
147
147
|
print("\nDensity mechanism layout:")
|
|
148
148
|
print("layout.kind:", layout.kind)
|
|
149
149
|
print("layout.target:", layout.target)
|
|
150
150
|
print("layout.n_active:", layout.n_active)
|
|
151
151
|
print("layout.source_cv_ids:", layout.source_cv_ids)
|
|
152
|
-
print("layout
|
|
153
|
-
print("
|
|
154
|
-
print("sample E at one active point:", channel_cell.get_point_state(point_id)[layout.id]["E"])
|
|
152
|
+
print("g_max on the density layout:", channel_cell.get_state(layout.id, "g_max"))
|
|
153
|
+
print("E on the density layout:", channel_cell.get_state(layout.id, "E"))
|
|
155
154
|
|
|
156
155
|
|
|
157
156
|
# 10. place(...): point mechanisms.
|
|
158
|
-
# place(locset, mechanism) attaches point mechanisms such as clamps
|
|
157
|
+
# place(locset, mechanism) attaches point mechanisms such as clamps.
|
|
159
158
|
place_cell = Cell(morpho, cv_policy=CVPerBranch(2))
|
|
160
159
|
place_cell.place(
|
|
161
160
|
RootLocation(x=0.5),
|
|
@@ -173,12 +172,11 @@ print("layout.n_active:", layout.n_active)
|
|
|
173
172
|
print("layout.point_index:", layout.point_index.tolist())
|
|
174
173
|
print("amplitudes:", place_cell.get_state(layout.id, "amplitudes"))
|
|
175
174
|
print("durations:", place_cell.get_state(layout.id, "durations"))
|
|
176
|
-
print("start:", place_cell.get_state(layout.id, "start"))
|
|
177
175
|
|
|
178
176
|
|
|
179
177
|
# 11. Minimal runnable multicompartment simulation.
|
|
180
178
|
# This is the canonical Cell(morpho) simulation shape: choose CV policy and solver,
|
|
181
|
-
# paint density mechanisms, place
|
|
179
|
+
# paint density mechanisms, place the clamp, register voltage, initialize, and run.
|
|
182
180
|
sim_cell = Cell(
|
|
183
181
|
morpho,
|
|
184
182
|
cv_policy=CVPerBranch(cv_per_branch=2),
|
|
@@ -197,10 +195,7 @@ sim_cell.place(
|
|
|
197
195
|
CurrentClamp(delay=20.0 * u.ms, durations=60.0 * u.ms, amplitudes=0.2 * u.nA),
|
|
198
196
|
)
|
|
199
197
|
|
|
200
|
-
sim_cell.
|
|
201
|
-
at("soma", 0.5),
|
|
202
|
-
StateProbe(),
|
|
203
|
-
)
|
|
198
|
+
sim_cell.loc(at("soma", 0.5)).record("soma_v", braincell.observe.state("v"))
|
|
204
199
|
|
|
205
200
|
sim_cell.init_state()
|
|
206
201
|
sim_cell.reset_state()
|
|
@@ -209,8 +204,9 @@ dt = 0.1 * u.ms
|
|
|
209
204
|
duration = 100.0 * u.ms
|
|
210
205
|
result = sim_cell.run(dt=dt, duration=duration)
|
|
211
206
|
|
|
212
|
-
|
|
213
|
-
|
|
207
|
+
voltage = result.samples["soma_v"]
|
|
208
|
+
times_ms = voltage.time.to_decimal(u.ms)
|
|
209
|
+
soma_v_mV = voltage.values[:, 0].to_decimal(u.mV)
|
|
214
210
|
|
|
215
211
|
plt.figure(figsize=(6, 4))
|
|
216
212
|
plt.plot(times_ms, soma_v_mV, label="soma(0.5)_v")
|
|
@@ -263,6 +263,3 @@ Verify `postsynaptic_input.shape == connectivity.shape[1:]` for vector input and
|
|
|
263
263
|
## Application script examples
|
|
264
264
|
| Reference | Open when |
|
|
265
265
|
|---|---|
|
|
266
|
-
| `references/scripts/coba_ei_teaching.py` | Open for the shared BrainEvent and BrainPy teaching example; it uses `BinaryArray` with interchangeable `FixedNumPerPre`, `CSR`, and dense connectivity for efficient event-driven communication into BrainPy `LIFRef`, `Expon`, and `COBA` dynamics inside one compiled BrainState loop. |
|
|
267
|
-
| `references/scripts/102_EI_net_1996.py` | Open for a complete high-level E/I network already using `brainpy.state.AlignPostProj` and `brainstate.nn.EventFixedProb`; it preserves unit-aware weights, initialization, compiled time loops, and visualization. |
|
|
268
|
-
| `references/scripts/204_joglekar_2018_propagation.py` | Open for delayed spikes, area mapping, and vmapped `JITCScalarC` communication; it preserves delays, seeds, external-data assumptions, and BrainPy compatibility details. |
|
|
@@ -125,5 +125,5 @@ Open the official Synaptic Plasticity tutorial when choosing trace equations, up
|
|
|
125
125
|
|
|
126
126
|
## Sources
|
|
127
127
|
|
|
128
|
-
-
|
|
128
|
+
- [Event-driven synaptic plasticity tutorial](https://brainx.chaobrain.com/brainevent/tutorials/events/synaptic-plasticity.html)
|
|
129
129
|
- Apply event-driven synaptic plasticity: https://brainx.chaobrain.com/brainevent/how-to/data-structures/synaptic-plasticity.html
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
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
|
|
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 BrainSpike and/or BrainCell when aggregate dynamics participate in a multiscale model.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# BrainMass
|
|
@@ -40,11 +40,13 @@ A noise process represents unresolved fluctuations or stochastic drive. It is at
|
|
|
40
40
|
|
|
41
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
42
|
|
|
43
|
+
Separate the catalog's scientific abstraction from the runner's compatibility. For a custom continuous-rate `brainstate.nn.Module`, evaluate `Simulator` against its initialization/update contract before choosing a manual rollout; using the runner does not pool individual units or replace their equations. Reject it for a concrete contract limitation, not merely because the custom model differs from the population-model catalog.
|
|
44
|
+
|
|
43
45
|
| API | Description |
|
|
44
46
|
|---|---|
|
|
45
47
|
| `brainmass.list_models()` | Use before choosing a model; it returns `ModelInfo` records with name, category, state-variable count, and use case. |
|
|
46
48
|
| `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 run path; it stores the model and integration step without changing the model equations. |
|
|
49
|
+
| `brainmass.Simulator(model, dt=...)` | Use for the default run path, including compatible custom Modules; it stores the model and integration step without changing the model equations. |
|
|
48
50
|
| `Simulator.run(duration, *, inputs=None, monitors=None, transient=None, sample_every=None, batch_size=None, init_states=True, jit=True)` | Use to drive and observe the model through the standard runner; it initializes State by default, executes the complete State-aware loop with JIT by default, applies transient removal and post-update sampling, and returns time-major trajectories plus unit-aware `ts`. |
|
|
49
51
|
|
|
50
52
|
```python
|
|
@@ -265,7 +267,7 @@ Choose the workflow category first, then open only the smallest reference that o
|
|
|
265
267
|
| `references/datasets-api.md` | Loading, inspecting, generating, or registering BrainMass data containers. |
|
|
266
268
|
| `references/coupling-network-api.md` | Selecting or configuring coupling, delays, connectivity conventions, direct coupling objects, or trainable network parameters. |
|
|
267
269
|
| `references/forward-observation-api.md` | Selecting BOLD, HRF kernels, temporal averaging, EEG/MEG lead fields, or trainable readouts. |
|
|
268
|
-
| `references/visualization-analysis-api.md` | Plotting or computing time-series, FC, FCD, and spectral summaries. |
|
|
270
|
+
| `references/visualization-analysis-api.md` | Plotting or computing sample-by-signal Pearson similarity, time-series, FC, FCD, and spectral summaries. |
|
|
269
271
|
|
|
270
272
|
### Fitting and regime exploration
|
|
271
273
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# BrainState constrained and regularized parameters
|
|
2
2
|
|
|
3
|
-
Use this reference after `
|
|
3
|
+
Use this reference after `brainmass` → `SKILL.md` has selected
|
|
4
4
|
`brainstate.nn.Param` for a fitted or directly trained BrainMass value that
|
|
5
5
|
needs a valid-domain transform, a regularization penalty, a modeling prior, or
|
|
6
6
|
fixed parameter-like storage. It owns the operational workflow and common
|
|
@@ -21,7 +21,7 @@ Keep `brainstate.nn` parameter transforms separate from execution transforms suc
|
|
|
21
21
|
|
|
22
22
|
## Parameter contract
|
|
23
23
|
|
|
24
|
-
A `ParamState`
|
|
24
|
+
A `ParamState` holds a trainable array or PyTree. `brainstate.nn.Param` layers two orthogonal concerns on top of it: a constraint transform and a regularization term.
|
|
25
25
|
|
|
26
26
|
- `param.val` is the underlying `ParamState`; optimizers update its unconstrained array.
|
|
27
27
|
- `param.value()` applies the forward transform and returns the constrained model-space value. With the default `IdentityT`, constrained and unconstrained values coincide.
|
|
@@ -45,6 +45,7 @@ This workflow keeps optimizer targets in unconstrained `ParamState`s, reads tran
|
|
|
45
45
|
import brainstate
|
|
46
46
|
from brainstate import nn
|
|
47
47
|
import brainunit as u
|
|
48
|
+
import braintools
|
|
48
49
|
import jax.numpy as jnp
|
|
49
50
|
|
|
50
51
|
|
|
@@ -69,6 +70,8 @@ class ConstrainedLinear(nn.Module):
|
|
|
69
70
|
|
|
70
71
|
model = ConstrainedLinear(4, 2)
|
|
71
72
|
params = model.states(brainstate.ParamState)
|
|
73
|
+
optimizer = braintools.optim.SGD(lr=0.1)
|
|
74
|
+
optimizer.register_trainable_weights(params)
|
|
72
75
|
x = brainstate.random.randn(16, 4)
|
|
73
76
|
y = brainstate.random.randn(16, 2)
|
|
74
77
|
|
|
@@ -82,11 +85,10 @@ def loss_fn():
|
|
|
82
85
|
def train_step():
|
|
83
86
|
grads, loss = brainstate.transform.grad(
|
|
84
87
|
loss_fn,
|
|
85
|
-
params,
|
|
88
|
+
grad_states=params,
|
|
86
89
|
return_value=True,
|
|
87
90
|
)()
|
|
88
|
-
|
|
89
|
-
params[key].value -= 0.1 * grads[key]
|
|
91
|
+
optimizer.update(grads)
|
|
90
92
|
return loss
|
|
91
93
|
```
|
|
92
94
|
|
|
@@ -161,7 +163,7 @@ Open `parameter-transforms-regularizers-catalog.md` to select classical, structu
|
|
|
161
163
|
Official sources:
|
|
162
164
|
|
|
163
165
|
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
164
|
-
- https://brainx.chaobrain.com/brainstate/apis/nn/
|
|
166
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html#standard-regularizations
|
|
165
167
|
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.ChainedReg.html
|
|
166
168
|
|
|
167
169
|
## Fixed values with `nn.Const`
|
|
@@ -209,6 +211,6 @@ Official sources:
|
|
|
209
211
|
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
210
212
|
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
211
213
|
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
212
|
-
- https://brainx.chaobrain.com/brainstate/apis/nn/
|
|
214
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html#standard-regularizations
|
|
213
215
|
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Param.html
|
|
214
216
|
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Const.html
|
|
@@ -100,7 +100,7 @@ Official sources:
|
|
|
100
100
|
|
|
101
101
|
Official sources:
|
|
102
102
|
|
|
103
|
-
- https://brainx.chaobrain.com/brainstate/apis/nn/
|
|
103
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html#standard-regularizations
|
|
104
104
|
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Regularization.html
|
|
105
105
|
- https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.ChainedReg.html
|
|
106
106
|
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_regularization.py
|
|
@@ -124,7 +124,7 @@ Official sources:
|
|
|
124
124
|
|
|
125
125
|
Use the generated class page for exact axes, reduction behavior, weights, and initialization arguments; these differ by regularizer and should not be inferred from neighboring classes.
|
|
126
126
|
|
|
127
|
-
Official source: https://brainx.chaobrain.com/brainstate/apis/nn/
|
|
127
|
+
Official source: https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html#standard-regularizations
|
|
128
128
|
|
|
129
129
|
## Prior-distribution regularizer selection
|
|
130
130
|
|
|
@@ -146,7 +146,7 @@ Prior regularizers encode distributional assumptions for Bayesian-inspired param
|
|
|
146
146
|
| Variable selection | `SpikeAndSlabReg` |
|
|
147
147
|
| Probability simplex | `DirichletReg` |
|
|
148
148
|
|
|
149
|
-
Official source: https://brainx.chaobrain.com/brainstate/apis/nn/
|
|
149
|
+
Official source: https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html#prior-distribution-based-regularizations
|
|
150
150
|
|
|
151
151
|
## Interaction safeguards
|
|
152
152
|
|
|
@@ -163,7 +163,7 @@ Official source: https://brainx.chaobrain.com/brainstate/apis/nn/regularization.
|
|
|
163
163
|
## Mirror source urls
|
|
164
164
|
|
|
165
165
|
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
|
|
166
|
-
- https://brainx.chaobrain.com/brainstate/apis/nn/
|
|
166
|
+
- https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html#standard-regularizations
|
|
167
167
|
- https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
|
|
168
168
|
- https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
|
|
169
169
|
- https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_param.py
|
|
@@ -28,14 +28,18 @@ preserve.
|
|
|
28
28
|
|
|
29
29
|
## Spike encoders
|
|
30
30
|
|
|
31
|
+
Import encoders from `braintools.spike`. The examples require BrainTools
|
|
32
|
+
0.4.0 or newer.
|
|
33
|
+
|
|
31
34
|
All encoder objects are reusable callables. Pass the input as the first argument
|
|
32
|
-
and the number of encoded timesteps as `n_time=`.
|
|
35
|
+
and the number of encoded timesteps as `n_time=`. Set the BrainState
|
|
36
|
+
sampling interval before encoding.
|
|
33
37
|
|
|
34
38
|
| API | Description |
|
|
35
39
|
|---|---|
|
|
36
40
|
| `LatencyEncoder(min_val=None, max_val=None, method='log', threshold=0.01, clip=False, tau=1 * u.ms, normalize=False, first_spk_time=0 * u.ms, epsilon=1e-7)` | Use for time-to-first-spike coding. Normalize inputs when they are not already in `[0, 1]`; larger values produce earlier spikes. |
|
|
37
41
|
| `RateEncoder(gain=100.0, method='linear', min_rate=0.0, max_rate=None, normalize=False, min_val=None, max_val=None)` | Use when firing rate should vary with input intensity. Select the mapping with `method` and constrain rates deliberately. |
|
|
38
|
-
| `PoissonEncoder(
|
|
42
|
+
| `PoissonEncoder(normalize=False, max_rate=100.0)` | Use when an input rate should generate Poisson-distributed spikes. Increase the observation window before judging whether empirical counts match the requested rate. |
|
|
39
43
|
| `PopulationEncoder(n_neurons, min_val=0.0, max_val=1.0, sigma=None, max_rate=100.0)` | Use to encode each scalar with overlapping population receptive fields. Set the represented range and population width explicitly. |
|
|
40
44
|
| `BernoulliEncoder(scale=1.0, normalize=True, min_val=None, max_val=None)` | Use for independent Bernoulli sampling at every time step. Ensure the resulting probabilities remain valid after scaling. |
|
|
41
45
|
| `DeltaEncoder(threshold=0.1, positive_only=False, absolute=False, normalize=True)` | Use for change detection in a temporal signal. Configure sign handling so negative changes are either retained, suppressed, or folded by absolute value. |
|
|
@@ -45,12 +49,15 @@ and the number of encoded timesteps as `n_time=`.
|
|
|
45
49
|
| `RankOrderEncoder(use_values=True, normalize=True, invert=False)` | Use when feature rank determines spike order. Use `invert=True` only when low-valued features must spike first. |
|
|
46
50
|
|
|
47
51
|
```python
|
|
52
|
+
import brainstate
|
|
53
|
+
import brainunit as u
|
|
48
54
|
import jax.numpy as jnp
|
|
49
|
-
from braintools import LatencyEncoder
|
|
55
|
+
from braintools.spike import LatencyEncoder
|
|
50
56
|
|
|
51
57
|
values = jnp.array([0.02, 0.5, 1.0])
|
|
52
|
-
encoder = LatencyEncoder(method="linear", normalize=True)
|
|
53
|
-
|
|
58
|
+
encoder = LatencyEncoder(method="linear", normalize=True, tau=4 * u.ms)
|
|
59
|
+
with brainstate.environ.context(dt=1 * u.ms):
|
|
60
|
+
spikes = encoder(values, n_time=5)
|
|
54
61
|
|
|
55
62
|
assert spikes.shape == (5, 3)
|
|
56
63
|
assert jnp.argmax(spikes[:, 2]) < jnp.argmax(spikes[:, 1])
|
|
@@ -78,6 +85,7 @@ tensors with broadcast-compatible shapes.
|
|
|
78
85
|
Do not use these helpers as fuzzy arithmetic on rates or arbitrary continuous
|
|
79
86
|
arrays; their formulas assume binary values.
|
|
80
87
|
|
|
81
|
-
## Official
|
|
88
|
+
## Official sources
|
|
82
89
|
|
|
83
|
-
-
|
|
90
|
+
- [BrainTools 0.4 encoder migration](https://github.com/chaobrain/braintools/releases/tag/v0.4.0)
|
|
91
|
+
- [Spike encoders and operations API](https://brainx.chaobrain.com/braintools/apis/spike.html)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
#
|
|
1
|
+
# BrainTools losses and analysis
|
|
2
2
|
|
|
3
3
|
Use this reference to select supervised losses and neuroscience metrics for
|
|
4
4
|
classification, regression, spike trains, local field potentials, correlation,
|
|
@@ -10,32 +10,36 @@ FC, and FCD comparisons. Use this reference for HORN supervised losses,
|
|
|
10
10
|
held-out metrics, or a custom fitting statistic not owned by
|
|
11
11
|
`brainmass.objectives`.
|
|
12
12
|
|
|
13
|
+
Use `braintools.metric` for training losses and vector comparisons. Use
|
|
14
|
+
`braintools.analysis` for neuroscience analysis. The analysis examples require
|
|
15
|
+
BrainTools 0.4.0 or newer.
|
|
16
|
+
|
|
13
17
|
## Choose a metric family
|
|
14
18
|
|
|
15
19
|
| Task | Use | Important constraint |
|
|
16
20
|
|---|---|---|
|
|
17
21
|
| Independent binary or multilabel classification | Sigmoid binary cross entropy or focal loss | Logits and labels must have broadcast-compatible class structure. |
|
|
18
22
|
| Mutually exclusive classes | Softmax cross entropy | Choose one-hot/probability labels or the integer-label variant explicitly. |
|
|
19
|
-
| Continuous fitting | Squared, absolute, Huber, log-cosh, or cosine losses |
|
|
23
|
+
| Continuous fitting | Squared, absolute, Huber, log-cosh, or cosine losses | Check the function-specific reduction and reduce explicitly when a scalar is required. |
|
|
20
24
|
| Spike timing | Victor-Purpura or van Rossum distance | Inputs are spike-time trains, not dense spike matrices. |
|
|
21
25
|
| Population spiking | Firing-rate and synchrony metrics | Dense spike matrices are time-major unless the API says otherwise. |
|
|
22
|
-
| LFP spectrum or coupling | PSD, coherence, PAC, CSD, entropy, or phase coherence |
|
|
26
|
+
| LFP spectrum or coupling | PSD, coherence, PAC, CSD, entropy, or phase coherence | For spectral routines with `dt`, pass the sample interval. CSD takes electrode spacing. |
|
|
23
27
|
| Functional connectivity | Correlation and connectivity functions | Time series use `(num_time, num_signals)`. |
|
|
24
28
|
|
|
25
|
-
## Classification losses
|
|
29
|
+
## Classification losses (`braintools.metric`)
|
|
26
30
|
|
|
27
31
|
| API | Description |
|
|
28
32
|
|---|---|
|
|
29
33
|
| `sigmoid_binary_cross_entropy(logits, labels)` | Use for independent binary classes; returns element-wise sigmoid cross entropy. |
|
|
30
34
|
| `softmax_cross_entropy(logits, labels)` | Use for mutually exclusive classes represented by one-hot or probability labels. |
|
|
31
|
-
| `softmax_cross_entropy_with_integer_labels(logits, labels)` | Use the more direct integer-index form for mutually exclusive classes.
|
|
35
|
+
| `softmax_cross_entropy_with_integer_labels(logits, labels)` | Use the more direct integer-index form for mutually exclusive classes. |
|
|
32
36
|
| `hinge_loss(...)` | Use for binary margin classification. |
|
|
33
37
|
| `perceptron_loss(...)` | Use for the binary perceptron objective. |
|
|
34
38
|
| `multiclass_hinge_loss(...)` | Use for a multiclass margin objective. |
|
|
35
39
|
| `multiclass_perceptron_loss(...)` | Use for a multiclass perceptron objective. |
|
|
36
40
|
| `poly_loss_cross_entropy(...)` | Use when the specified method requires PolyLoss cross entropy. |
|
|
37
|
-
| `kl_divergence(
|
|
38
|
-
| `kl_divergence_with_log_targets(...)` | Use when
|
|
41
|
+
| `kl_divergence(log_predictions, targets)` | Compare target probabilities with predicted log probabilities. |
|
|
42
|
+
| `kl_divergence_with_log_targets(...)` | Use when both predicted and target probabilities are supplied in log space. |
|
|
39
43
|
| `convex_kl_divergence(...)` | Use when the convex KL variant is required. |
|
|
40
44
|
| `ctc_loss(...)` | Use for sequence alignment without frame-level labels. |
|
|
41
45
|
| `ctc_loss_with_forward_probs(...)` | Use when the CTC forward probabilities are also needed. |
|
|
@@ -59,19 +63,18 @@ loss = jnp.mean(per_example)
|
|
|
59
63
|
assert loss.ndim == 0
|
|
60
64
|
```
|
|
61
65
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
`
|
|
65
|
-
labels.
|
|
66
|
+
Validate integer labels against `0 <= labels < logits.shape[-1]` before
|
|
67
|
+
computing the loss. Invalid indices can select a different class or return
|
|
68
|
+
`NaN` without raising.
|
|
66
69
|
|
|
67
|
-
## Regression and pairwise metrics
|
|
70
|
+
## Regression and pairwise metrics (`braintools.metric`)
|
|
68
71
|
|
|
69
72
|
| API | Description |
|
|
70
73
|
|---|---|
|
|
71
|
-
| `squared_error(predictions, targets=None, axis=None, reduction='none')` | Use for element-wise squared error; choose `mean`
|
|
74
|
+
| `squared_error(predictions, targets=None, axis=None, reduction='none')` | Use for element-wise squared error. Targets must match prediction shape; choose `reduction="mean"` for a scalar MSE with `axis=None`. |
|
|
72
75
|
| `absolute_error(...)` | Use for element-wise absolute error. |
|
|
73
|
-
| `l1_loss(
|
|
74
|
-
| `l2_loss(...)` | Use for squared
|
|
76
|
+
| `l1_loss(logits, targets, reduction="mean")` | Average absolute error over non-batch axes first; use `reduction="none"` to keep one value per sample. |
|
|
77
|
+
| `l2_loss(...)` | Use for half the squared error. |
|
|
75
78
|
| `l2_norm(...)` | Return the L2 norm of prediction error. |
|
|
76
79
|
| `safe_norm(...)` | Use when a differentiable lower bound must prevent an unstable zero norm. |
|
|
77
80
|
| `huber_loss(predictions, targets=None, delta=1.0, axis=None, reduction='none')` | Use for quadratic small residuals and linear large residuals; tune `delta` in target units. |
|
|
@@ -85,38 +88,42 @@ Do not conflate element-wise loss with final optimization reduction. Preserve
|
|
|
85
88
|
batch and time axes until the scientific loss definition determines how to
|
|
86
89
|
reduce them.
|
|
87
90
|
|
|
88
|
-
## Correlation and functional connectivity
|
|
91
|
+
## Correlation and functional connectivity (`braintools.analysis`)
|
|
89
92
|
|
|
90
93
|
| API | Description |
|
|
91
94
|
|---|---|
|
|
92
|
-
| `cross_correlation(spikes, bin, dt)` | Calculate a cross-correlation synchrony index from a time-major spike matrix. |
|
|
93
|
-
| `voltage_fluctuation(
|
|
94
|
-
| `matrix_correlation(
|
|
95
|
-
| `weighted_correlation(x, y,
|
|
96
|
-
| `functional_connectivity(activities)` | Return the pairwise Pearson correlation matrix for `(num_time, num_signals)` data; NaNs are replaced with zero. |
|
|
97
|
-
| `functional_connectivity_dynamics(activities, window_size, step_size)` |
|
|
95
|
+
| `spike.cross_correlation(spikes, bin, dt=None, ...)` | Calculate a cross-correlation synchrony index from a time-major spike matrix. |
|
|
96
|
+
| `population.voltage_fluctuation(potentials, ...)` | Estimate synchrony from population voltage variance. |
|
|
97
|
+
| `stats.matrix_correlation(x, y)` | Correlate the strict upper triangles of two matching connectivity matrices. |
|
|
98
|
+
| `stats.weighted_correlation(x, y, w)` | Compute weighted Pearson correlation for two one-dimensional series. |
|
|
99
|
+
| `population.functional_connectivity(activities)` | Return the pairwise Pearson correlation matrix for `(num_time, num_signals)` data; NaNs are replaced with zero. |
|
|
100
|
+
| `population.functional_connectivity_dynamics(activities, window_size, step_size)` | Correlate the strict upper triangles of windowed FC matrices. Specify window size and step in samples. |
|
|
98
101
|
|
|
99
102
|
## Spike-train metrics
|
|
100
103
|
|
|
104
|
+
Pass physical time quantities on BrainTools 0.4. Bare `dt` values are in
|
|
105
|
+
seconds for `firing_rate`, `phase_locking_value`, and spectral functions.
|
|
106
|
+
Most other spike-matrix routines use milliseconds.
|
|
107
|
+
|
|
101
108
|
| API | Description |
|
|
102
109
|
|---|---|
|
|
103
|
-
| `
|
|
104
|
-
| `
|
|
105
|
-
| `
|
|
106
|
-
| `
|
|
107
|
-
| `
|
|
108
|
-
| `
|
|
109
|
-
| `
|
|
110
|
-
| `
|
|
111
|
-
| `correlation_index(spikes, window_size, dt=None)` | Compute a windowed spike-train correlation index. |
|
|
110
|
+
| `spike.firing_rate(spikes, width, dt=None)` | Return a time series of population rate in Hz. Pass physical time quantities for `width` and `dt` to make units explicit. |
|
|
111
|
+
| `spike.victor_purpura_distance(spike_times_1, spike_times_2, cost_factor=1.0)` | Measure edit cost from insertions, deletions, and temporal shifts. |
|
|
112
|
+
| `spike.van_rossum_distance(spike_times_1, spike_times_2, tau=1.0, t_max=None)` | Compare exponentially filtered spike trains. |
|
|
113
|
+
| `spike.spike_train_synchrony(spike_matrix, window_size, dt=None)` | Average pairwise spike coincidences within a time window. Silent-neuron pairs are omitted; check activity before interpreting the score. |
|
|
114
|
+
| `spike.burst_synchrony_index(spike_matrix, burst_threshold=3, max_isi=100.0, dt=None)` | Measure co-occurring burst events. |
|
|
115
|
+
| `spike.phase_locking_value(spike_matrix, reference_freq, dt=None)` | Measure spike phase locking at a specified reference frequency; this score does not give a signed phase lag. |
|
|
116
|
+
| `spike.spike_time_tiling_coefficient(spike_matrix, dt=None, tau=5.0)` | Compute STTC within a temporal tolerance. |
|
|
117
|
+
| `spike.correlation_index(spike_matrix, window_size, dt=None)` | Compute a windowed spike-train correlation index. |
|
|
112
118
|
|
|
113
119
|
```python
|
|
114
120
|
import brainunit as u
|
|
115
|
-
|
|
121
|
+
import braintools
|
|
122
|
+
import jax.numpy as jnp
|
|
116
123
|
|
|
117
|
-
|
|
118
|
-
rate = firing_rate(spikes, width=10 * u.ms, dt=1 * u.ms)
|
|
119
|
-
synchrony = spike_train_synchrony(
|
|
124
|
+
spikes = jnp.zeros((200, 5)).at[50:53, :].set(1.0)
|
|
125
|
+
rate = braintools.analysis.spike.firing_rate(spikes, width=10 * u.ms, dt=1 * u.ms)
|
|
126
|
+
synchrony = braintools.analysis.spike.spike_train_synchrony(
|
|
120
127
|
spikes,
|
|
121
128
|
window_size=5 * u.ms,
|
|
122
129
|
dt=1 * u.ms,
|
|
@@ -125,26 +132,40 @@ synchrony = spike_train_synchrony(
|
|
|
125
132
|
|
|
126
133
|
Keep dense spike matrices and lists of spike times distinct. Distance metrics
|
|
127
134
|
consume event times; population rate and synchrony metrics consume matrices.
|
|
135
|
+
Use [`braintools.spike.SpikeTrains.from_dense`](https://brainx.chaobrain.com/braintools/apis/generated/braintools.spike.SpikeTrains.html#braintools.spike.SpikeTrains.from_dense)
|
|
136
|
+
to convert a regularly sampled matrix to spike trains; use
|
|
137
|
+
[`braintools.visualize.spike_raster`](https://brainx.chaobrain.com/braintools/apis/generated/braintools.visualize.spike_raster.html)
|
|
138
|
+
to draw a raster.
|
|
128
139
|
|
|
129
140
|
## Local field potential analysis
|
|
130
141
|
|
|
131
142
|
| API | Description |
|
|
132
143
|
|---|---|
|
|
133
|
-
| `unitary_LFP(times, spikes,
|
|
134
|
-
| `power_spectral_density(lfp, dt, nperseg=None, noverlap=None, freq_range=None)` | Return one-sided Welch frequencies and PSD. |
|
|
135
|
-
| `
|
|
136
|
-
| `
|
|
137
|
-
| `
|
|
138
|
-
| `
|
|
139
|
-
| `
|
|
140
|
-
| `
|
|
144
|
+
| `field.unitary_LFP(times, spikes, spike_type, ...)` | Construct unitary LFP contributions from spikes. Supply times in milliseconds and choose `'exc'` or `'inh'`. |
|
|
145
|
+
| `spectral.power_spectral_density(lfp, dt, nperseg=None, noverlap=None, freq_range=None)` | Return one-sided Welch frequencies in Hz and PSD for `(time,)` or `(time, channels)` input. |
|
|
146
|
+
| `spectral.spectrogram(x, dt, nperseg, noverlap=None, window='hann', detrend='constant')` | Use when segment spectra or explicit window/detrending controls are required; returns frequencies, segment centers and PSD shaped `(frequency, segment, ...)`. |
|
|
147
|
+
| `spectral.coherence_analysis(lfp1, lfp2, dt, ...)` | Return frequency-resolved magnitude-squared coherence. |
|
|
148
|
+
| `spectral.phase_amplitude_coupling(lfp, dt, phase_freq_range, amplitude_freq_range, ...)` | Return Tort modulation index plus phase-bin details. |
|
|
149
|
+
| `spectral.theta_gamma_coupling(lfp, dt)` | Return theta-gamma coupling using standard bands. |
|
|
150
|
+
| `field.current_source_density(lfp_laminar, electrode_spacing, conductivity=1.0, axis=-1)` | Estimate laminar CSD using electrode spacing. Set `axis` explicitly when electrodes are not on the last axis. |
|
|
151
|
+
| `spectral.spectral_entropy(lfp, dt, ...)` | Return normalized spectral entropy. |
|
|
152
|
+
| `spectral.lfp_phase_coherence(lfp_signals, dt, freq_band=(8, 12))` | Compute pairwise phase coherence across channels. |
|
|
153
|
+
|
|
154
|
+
Use `power_spectral_density` when its estimator defaults match the protocol.
|
|
155
|
+
For a fixed Welch estimator requiring explicit window and detrending controls,
|
|
156
|
+
use [`spectral.spectrogram`](https://brainx.chaobrain.com/braintools/apis/generated/braintools.analysis.spectral.spectrogram.html)
|
|
157
|
+
and take `u.math.mean(segment_psd, axis=1)` over segments. Set `noverlap`
|
|
158
|
+
explicitly: its default is `nperseg // 8`, not 50%. `window='hann'` selects
|
|
159
|
+
a periodic Hann window; `detrend='constant'` removes each segment's mean.
|
|
160
|
+
For a Quantity signal with unit `U`, the segment PSD and its mean retain
|
|
161
|
+
`U**2 / Hz`. Preserve the frozen estimator when comparing implementations.
|
|
141
162
|
|
|
142
163
|
`power_spectral_density(..., freq_range=...)` uses boolean-mask indexing and
|
|
143
164
|
therefore has a data-dependent output length; that path is not JIT-compatible.
|
|
144
165
|
Compute the full spectrum inside JIT and filter outside when compilation is
|
|
145
166
|
required.
|
|
146
167
|
|
|
147
|
-
## Structured, ranking, and smoothing losses
|
|
168
|
+
## Structured, ranking, and smoothing losses (`braintools.metric`)
|
|
148
169
|
|
|
149
170
|
| API | Description |
|
|
150
171
|
|---|---|
|
|
@@ -152,6 +173,11 @@ required.
|
|
|
152
173
|
| `ranking_softmax_loss(scores, labels, ...)` | Use for list-wise learning-to-rank objectives. |
|
|
153
174
|
| `smooth_labels(labels, alpha=...)` | Apply label smoothing to one-hot targets. |
|
|
154
175
|
|
|
155
|
-
## Official
|
|
176
|
+
## Official sources
|
|
177
|
+
|
|
178
|
+
Open the [analysis API](https://brainx.chaobrain.com/braintools/apis/analysis.html)
|
|
179
|
+
for PSTH, interspike-interval statistics, or band power. Open the
|
|
180
|
+
[fitting API](https://brainx.chaobrain.com/braintools/apis/fit.html) when firing
|
|
181
|
+
rate, PSD, or FC is a fitting objective.
|
|
156
182
|
|
|
157
|
-
-
|
|
183
|
+
- [Training losses and deprecated alias routing](https://brainx.chaobrain.com/braintools/apis/metric.html)
|
|
@@ -224,6 +224,8 @@ assert traces.shape == (2, 200, 3)
|
|
|
224
224
|
|
|
225
225
|
Keep `max_delay` static. Constructing `Network` or `Delay` with a mapped delay can make buffer capacity depend on a tracer and fail during shape allocation. Map the complete independent condition, vary only the integer retrieval step, and preserve the same `dt` across construction, initialization, and execution.
|
|
226
226
|
|
|
227
|
+
This hand-written mapped rollout exists only because each lane owns a different delay and coupling value. Run one custom `brainstate.nn.Module` through `brainmass.Simulator(model, dt=...).run(...)`; do not rebuild initialization, the time loop, or monitoring for a single run.
|
|
228
|
+
|
|
227
229
|
Lock the phase convention with an impulse check before interpreting neural output:
|
|
228
230
|
|
|
229
231
|
```python
|
|
@@ -247,7 +249,7 @@ If retrieval occurs before insertion, the buffer still ends at the previous simu
|
|
|
247
249
|
|
|
248
250
|
## Application script
|
|
249
251
|
|
|
250
|
-
Open `scripts/resting-state-meg-whole-brain-pipeline.py` when the task needs the complete connectome-to-network-to-MEG-to-functional-connectivity workflow.
|
|
252
|
+
Open `references/scripts/resting-state-meg-whole-brain-pipeline.py` when the task needs the complete connectome-to-network-to-MEG-to-functional-connectivity workflow. The script requires BrainTools 0.4.0 or newer.
|
|
251
253
|
|
|
252
254
|
## Diagnose network failures
|
|
253
255
|
|
|
@@ -93,17 +93,17 @@ For scientific use, make `predict` return the observation space that matches the
|
|
|
93
93
|
|
|
94
94
|
Gradient-free backends need a finite box for every fitted parameter. Derive it from a finite parameter transform such as `SigmoidT(low, high)` or pass `search_space={name: (low, high)}`.
|
|
95
95
|
|
|
96
|
-
Open `scripts/gradient-free-fitting.py` for the complete shared-objective workflow with Nevergrad differential evolution and SciPy Nelder-Mead. Do not implement gradient-free fitting as only a `backend=` substitution because bounds and optimizer arguments also change.
|
|
96
|
+
Open `references/scripts/gradient-free-fitting.py` for the complete shared-objective workflow with Nevergrad differential evolution and SciPy Nelder-Mead. Do not implement gradient-free fitting as only a `backend=` substitution because bounds and optimizer arguments also change.
|
|
97
97
|
|
|
98
|
-
Open `scripts/eeg-fitting-with-gradients.py` when the task needs a complete Jansen-Rit workflow that constructs a phase-invariant EEG target, fits the connectivity parameter with gradients, and compares the recovered trace.
|
|
98
|
+
Open `references/scripts/eeg-fitting-with-gradients.py` when the task needs a complete Jansen-Rit workflow that constructs a phase-invariant EEG target, fits the connectivity parameter with gradients, and compares the recovered trace.
|
|
99
99
|
|
|
100
|
-
Open `brainstate/parameter-constraints-regularization.md` when a fitted
|
|
100
|
+
Open `references/brainstate/parameter-constraints-regularization.md` when a fitted
|
|
101
101
|
parameter needs a valid-domain transform, penalty, or modeling prior; that
|
|
102
102
|
reference routes to the exhaustive transform and regularizer catalog. Open
|
|
103
|
-
`braintools/parameter-initializer.md` when the starting value needs a reusable
|
|
104
|
-
initialization policy. Open `braintools/metric.md` only when a custom statistic
|
|
103
|
+
`references/braintools/parameter-initializer.md` when the starting value needs a reusable
|
|
104
|
+
initialization policy. Open `references/braintools/metric.md` only when a custom statistic
|
|
105
105
|
is not already owned by `brainmass.objectives`. Open
|
|
106
|
-
`braintools/optimizer.md` when choosing a gradient optimizer, schedule, or
|
|
106
|
+
`references/braintools/optimizer.md` when choosing a gradient optimizer, schedule, or
|
|
107
107
|
standalone optimizer family beyond the canonical `Adam` example.
|
|
108
108
|
|
|
109
109
|
## Interpret `FitResult`
|
|
@@ -46,9 +46,9 @@ assert targets.shape == (320,)
|
|
|
46
46
|
|
|
47
47
|
Create train and held-out splits before optimization. Do not report the training metric as generalization.
|
|
48
48
|
|
|
49
|
-
Open `braintools/cogtask.md` when a pre-built or custom phase-structured
|
|
49
|
+
Open `references/braintools/cogtask.md` when a pre-built or custom phase-structured
|
|
50
50
|
cognitive paradigm should generate the trials. Open
|
|
51
|
-
`braintools/data-preprocessing.md` only when custom inputs must be encoded before
|
|
51
|
+
`references/braintools/data-preprocessing.md` only when custom inputs must be encoded before
|
|
52
52
|
they enter HORN; the ordinary feature sequences above need no spike encoder.
|
|
53
53
|
|
|
54
54
|
## Build the classifier and reset hidden State
|
|
@@ -81,7 +81,7 @@ weights = network.states(brainstate.ParamState)
|
|
|
81
81
|
|
|
82
82
|
**Invariant:** reset hidden State for training and evaluation. A held-out evaluation that begins from training State is invalid.
|
|
83
83
|
|
|
84
|
-
Open `braintools/parameter-initializer.md` when HORN weights or model parameters
|
|
84
|
+
Open `references/braintools/parameter-initializer.md` when HORN weights or model parameters
|
|
85
85
|
need a reusable variance-scaling, orthogonal, bounded, or unit-aware
|
|
86
86
|
initialization policy.
|
|
87
87
|
|
|
@@ -111,7 +111,7 @@ def loss_and_accuracy(batch_inputs, batch_targets):
|
|
|
111
111
|
def train_step(batch_inputs, batch_targets):
|
|
112
112
|
gradient = brainstate.transform.grad(
|
|
113
113
|
lambda: loss_and_accuracy(batch_inputs, batch_targets),
|
|
114
|
-
weights,
|
|
114
|
+
grad_states=weights,
|
|
115
115
|
has_aux=True,
|
|
116
116
|
return_value=True,
|
|
117
117
|
)
|
|
@@ -126,8 +126,8 @@ def evaluate(batch_inputs, batch_targets):
|
|
|
126
126
|
|
|
127
127
|
If the installed Braintools release exposes `optimizer.update(grads)` instead
|
|
128
128
|
of `step(grads)`, use the installed optimizer contract consistently; do not mix
|
|
129
|
-
methods in one loop. Open `braintools/optimizer.md` for optimizer and scheduler
|
|
130
|
-
selection, and `braintools/metric.md` for supervised loss, reduction, and
|
|
129
|
+
methods in one loop. Open `references/braintools/optimizer.md` for optimizer and scheduler
|
|
130
|
+
selection, and `references/braintools/metric.md` for supervised loss, reduction, and
|
|
131
131
|
held-out metric selection.
|
|
132
132
|
|
|
133
133
|
## Run epochs and evaluate held-out data
|
|
@@ -166,7 +166,7 @@ for epoch in range(n_epoch):
|
|
|
166
166
|
|
|
167
167
|
Validate that chance-level accuracy, label balance, loss reduction, and held-out improvement are all consistent with the task. A final accuracy alone does not reveal leakage or class imbalance.
|
|
168
168
|
|
|
169
|
-
Open `scripts/horn-cognitive-task-training.py` when the task needs the complete delayed-match dataset, HORN network, compiled training loop, held-out evaluation, and learning curves.
|
|
169
|
+
Open `references/scripts/horn-cognitive-task-training.py` when the task needs the complete delayed-match dataset, HORN network, compiled training loop, held-out evaluation, and learning curves.
|
|
170
170
|
|
|
171
171
|
## Choose task-training variations
|
|
172
172
|
|
|
@@ -176,9 +176,9 @@ Open `scripts/horn-cognitive-task-training.py` when the task needs the complete
|
|
|
176
176
|
- Clip gradients only after confirming large or non-finite gradients.
|
|
177
177
|
- Tune oscillator `alpha`, `omega`, damping, and hidden size one decision at a time.
|
|
178
178
|
- Use direct Braintools metrics when the held-out criterion is not accuracy.
|
|
179
|
-
- Open `brainstate/parameter-constraints-regularization.md` when a directly
|
|
179
|
+
- Open `references/brainstate/parameter-constraints-regularization.md` when a directly
|
|
180
180
|
trained oscillator parameter needs a valid domain, penalty, or prior.
|
|
181
|
-
- Open `braintools/surrogate.md` only when a custom path introduces a hard
|
|
181
|
+
- Open `references/braintools/surrogate.md` only when a custom path introduces a hard
|
|
182
182
|
threshold or spike; canonical HORN training does not need a surrogate.
|
|
183
183
|
|
|
184
184
|
## Common failures
|