brainx-skill 1.0.15 → 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.
Files changed (171) hide show
  1. package/README.md +17 -1
  2. package/manifest.json +1 -1
  3. package/mcp-servers/codex/skills.json +1 -1
  4. package/package.json +1 -1
  5. package/skills/bio-neuro-lit/SKILL.md +4 -2
  6. package/skills/bio-neuro-lit/references/required-supplements.md +27 -0
  7. package/skills/brainx-acceleration/SKILL.md +30 -437
  8. package/skills/brainx-acceleration/references/audit-and-rewrite-patterns.md +326 -0
  9. package/skills/brainx-general-guard/SKILL.md +24 -8
  10. package/skills/brainx-install/SKILL.md +3 -3
  11. package/skills/brainx-install/references/compatibility-and-release-matching.md +28 -20
  12. package/skills/brainx-install/references/uninstall-and-cleanup.md +11 -4
  13. package/skills/brainx-modeling-loop/SKILL.md +117 -36
  14. package/skills/brainx-modeling-loop/agents/openai.yaml +2 -2
  15. package/skills/brainx-modeling-loop/references/mechanism-comparison.md +62 -0
  16. package/skills/brainx-modeling-loop/references/multiscale-coupling.md +16 -0
  17. package/skills/brainx-modeling-loop/references/paper-reproduction.md +42 -0
  18. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +14 -14
  19. package/skills/brainx-modeling-loop/references/run-experiment.md +1 -1
  20. package/skills/brainx-modeling-loop/references/training-workflow.md +10 -8
  21. package/skills/brainx-visualization/SKILL.md +6 -2
  22. package/skills/brainx-visualization/references/neural-data-visualization.md +1 -1
  23. package/skills/brainx-visualization/references/statistical-and-model-visualization.md +1 -1
  24. package/skills/package-skills/braincell/SKILL.md +23 -14
  25. package/skills/package-skills/braincell/references/braintools/input-current.md +1 -1
  26. package/skills/package-skills/braincell/references/braintools/metric.md +72 -46
  27. package/skills/package-skills/braincell/references/mixions-for-adaptation.md +1 -1
  28. package/skills/package-skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +1 -1
  29. package/skills/package-skills/braincell/references/multicompartment/cv-policy-reference.md +1 -1
  30. package/skills/package-skills/braincell/references/multicompartment/filter-function-library.md +3 -3
  31. package/skills/package-skills/braincell/references/multicompartment/morphology-io-loading-validation.md +1 -1
  32. package/skills/package-skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +31 -43
  33. package/skills/package-skills/braincell/references/multicompartment/network-workflow.md +49 -0
  34. package/skills/package-skills/braincell/references/multicompartment/probe-reference.md +26 -114
  35. package/skills/package-skills/braincell/references/multicompartment/topology-building-and-visualization.md +40 -28
  36. package/skills/package-skills/braincell/references/scripts/cell_multicompartment_reference.py +13 -17
  37. package/skills/package-skills/brainevent/SKILL.md +0 -3
  38. package/skills/package-skills/brainevent/references/synaptic-plasticity.md +1 -1
  39. package/skills/package-skills/brainmass/SKILL.md +5 -3
  40. package/skills/package-skills/brainmass/references/brainstate/parameter-constraints-regularization.md +9 -7
  41. package/skills/package-skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
  42. package/skills/package-skills/brainmass/references/braintools/data-preprocessing.md +15 -7
  43. package/skills/package-skills/brainmass/references/braintools/metric.md +72 -46
  44. package/skills/package-skills/brainmass/references/coupling-network-api.md +3 -1
  45. package/skills/package-skills/brainmass/references/fitting-with-objectives-api.md +6 -6
  46. package/skills/package-skills/brainmass/references/horn-task-training.md +9 -9
  47. package/skills/package-skills/brainmass/references/modellibrary.md +12 -10
  48. package/skills/package-skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +5 -3
  49. package/skills/package-skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +10 -6
  50. package/skills/package-skills/brainmass/references/simulator-input-monitor-api.md +3 -1
  51. package/skills/package-skills/brainmass/references/visualization-analysis-api.md +17 -9
  52. package/skills/package-skills/brainspike/SKILL.md +201 -0
  53. package/skills/package-skills/brainspike/references/braintools/connectivity.md +40 -0
  54. package/skills/package-skills/brainspike/references/braintools/data-preprocessing.md +39 -0
  55. package/skills/package-skills/brainspike/references/braintools/input-current.md +55 -0
  56. package/skills/package-skills/brainspike/references/braintools/metric.md +36 -0
  57. package/skills/package-skills/brainspike/references/braintools/optimizer.md +50 -0
  58. package/skills/package-skills/brainspike/references/braintools/parameter-initializer.md +43 -0
  59. package/skills/package-skills/brainspike/references/braintools/surrogate.md +40 -0
  60. package/skills/package-skills/brainspike/references/migration-boundary.md +38 -0
  61. package/skills/package-skills/brainspike/references/model-and-readout-selection.md +41 -0
  62. package/skills/package-skills/brainspike/references/multirate-coupling.md +31 -0
  63. package/skills/package-skills/brainspike/references/multiscale-composition.md +28 -0
  64. package/skills/package-skills/brainspike/references/native-composition.md +52 -0
  65. package/skills/package-skills/brainspike/references/native-delays.md +34 -0
  66. package/skills/package-skills/brainspike/references/native-projections.md +43 -0
  67. package/skills/package-skills/brainspike/references/native-training.md +36 -0
  68. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/devices.md +33 -33
  69. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/divergence-and-parity.md +15 -15
  70. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/integration-categories.md +1 -1
  71. package/skills/package-skills/brainspike/references/nest-compatible/model-library.md +200 -0
  72. package/skills/package-skills/brainspike/references/nest-compatible/network-building.md +276 -0
  73. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brette_et_al_2007.py +23 -26
  74. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_alpha.py +18 -21
  75. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_delta.py +16 -19
  76. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +11 -12
  77. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +10 -11
  78. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/spatial_gaussex.py +18 -18
  79. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/synapsecollection.py +26 -29
  80. package/skills/package-skills/brainspike/references/nest-compatible/synapse-and-connectivity.md +166 -0
  81. package/skills/package-skills/brainspike/references/nest-delay-boundaries.md +31 -0
  82. package/skills/package-skills/brainspike/references/nonlinear-state-sharing.md +26 -0
  83. package/skills/package-skills/{brainpy-state → brainspike}/references/perturbation-experiment-validity.md +2 -2
  84. package/skills/package-skills/brainspike/references/simulator-training.md +61 -0
  85. package/skills/package-skills/brainspike/references/temporal-task-training.md +36 -0
  86. package/skills/package-skills/brainspike/scripts/advanced_native_patterns.py +76 -0
  87. package/skills/package-skills/brainspike/scripts/delay_workflow.py +44 -0
  88. package/skills/package-skills/brainspike/scripts/delayed_cue_training.py +78 -0
  89. package/skills/package-skills/brainspike/scripts/lif_smoke.py +31 -0
  90. package/skills/package-skills/brainspike/scripts/multiscale_workflow.py +35 -0
  91. package/skills/package-skills/brainspike/scripts/native_ei_network.py +47 -0
  92. package/skills/package-skills/brainspike/scripts/native_workflows.py +77 -0
  93. package/skills/package-skills/brainspike/scripts/nest_boundary_workflows.py +108 -0
  94. package/skills/package-skills/brainspike/scripts/train_native_snn.py +65 -0
  95. package/skills/package-skills/brainspike/scripts/train_nest_simulator.py +69 -0
  96. package/skills/package-skills/brainspike/scripts/train_nest_simulator_two_weights.py +220 -0
  97. package/skills/package-skills/brainstate/SKILL.md +16 -21
  98. package/skills/package-skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +1 -138
  99. package/skills/package-skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
  100. package/skills/package-skills/brainstate/references/brainstate/delay-buffers.md +45 -0
  101. package/skills/package-skills/brainstate/references/brainstate/parameter-constraints-regularization.md +9 -7
  102. package/skills/package-skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
  103. package/skills/package-skills/brainstate/references/brainstate/randomness-and-reproducibility.md +6 -4
  104. package/skills/package-skills/brainstate/references/brainstate/transformation-grad-expansion.md +4 -4
  105. package/skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md +1 -1
  106. package/skills/package-skills/brainstate/references/braintools-optimizer-reference.md +16 -0
  107. package/skills/package-skills/brainstate/references/libraries/prebuilt-layer-library.md +1 -1
  108. package/skills/package-skills/brainstate/references/simulation-environment.md +5 -5
  109. package/skills/package-skills/braintrace/SKILL.md +17 -38
  110. package/skills/package-skills/braintrace/references/Drtrl.md +9 -26
  111. package/skills/package-skills/braintrace/references/algorithm selection.md +7 -12
  112. package/skills/package-skills/braintrace/references/batching.md +15 -35
  113. package/skills/package-skills/braintrace/references/compiler_internal.md +1 -1
  114. package/skills/package-skills/braintrace/references/custom algorithms.md +1 -2
  115. package/skills/package-skills/braintrace/references/customizing_primitive_transforms.md +26 -15
  116. package/skills/package-skills/braintrace/references/pp_pprop workflow.md +5 -139
  117. package/skills/package-skills/brainunit/SKILL.md +7 -2
  118. package/skills/package-skills/brainunit/references/array-mechanics/functional-structural-api.md +1 -1
  119. package/skills/package-skills/brainunit/references/math-function-library.md +2 -2
  120. package/skills/package-skills/brainunit/references/typing-and-runtime-validation.md +5 -2
  121. package/skills/package-skills/brainevent/references/scripts/102_EI_net_1996.py +0 -107
  122. package/skills/package-skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +0 -168
  123. package/skills/package-skills/brainevent/references/scripts/coba_ei_teaching.py +0 -356
  124. package/skills/package-skills/brainpy-state/SKILL.md +0 -247
  125. package/skills/package-skills/brainpy-state/references/array-creation.md +0 -158
  126. package/skills/package-skills/brainpy-state/references/brain-dynamics-delay-protocol.md +0 -147
  127. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/analysis.md +0 -150
  128. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +0 -373
  129. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -150
  130. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +0 -175
  131. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +0 -286
  132. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +0 -111
  133. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -163
  134. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -113
  135. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -136
  136. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -222
  137. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -123
  138. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +0 -107
  139. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -185
  140. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/integrators.md +0 -181
  141. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +0 -102
  142. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +0 -147
  143. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +0 -159
  144. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +0 -127
  145. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +0 -167
  146. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +0 -107
  147. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -186
  148. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +0 -104
  149. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +0 -89
  150. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +0 -253
  151. package/skills/package-skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +0 -334
  152. package/skills/package-skills/brainpy-state/references/braintools/connectivity.md +0 -206
  153. package/skills/package-skills/brainpy-state/references/braintools/data-preprocessing.md +0 -79
  154. package/skills/package-skills/brainpy-state/references/braintools/input-current.md +0 -199
  155. package/skills/package-skills/brainpy-state/references/braintools/metric.md +0 -152
  156. package/skills/package-skills/brainpy-state/references/braintools/optimizer.md +0 -179
  157. package/skills/package-skills/brainpy-state/references/braintools/parameter-initializer.md +0 -183
  158. package/skills/package-skills/brainpy-state/references/braintools/surrogate.md +0 -147
  159. package/skills/package-skills/brainpy-state/references/component-selection.md +0 -288
  160. package/skills/package-skills/brainpy-state/references/nest-compatible/model-library.md +0 -200
  161. package/skills/package-skills/brainpy-state/references/nest-compatible/nest-workflow.md +0 -156
  162. package/skills/package-skills/brainpy-state/references/nest-compatible/network-building.md +0 -264
  163. package/skills/package-skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +0 -153
  164. package/skills/package-skills/brainpy-state/references/projection-patterns.md +0 -127
  165. package/skills/package-skills/brainpy-state/references/scripts/103_COBA_2005.py +0 -86
  166. package/skills/package-skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +0 -181
  167. package/skills/package-skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +0 -156
  168. package/skills/package-skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +0 -111
  169. package/skills/package-skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -221
  170. package/skills/package-skills/brainpy-state/references/scripts/sound_localization.py +0 -240
  171. package/skills/package-skills/brainpy-state/references/scripts/training-snn.py +0 -119
@@ -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(time_window=1000.0, 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. |
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
- spikes = encoder(values, n_time=5)
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 source
88
+ ## Official sources
82
89
 
83
- - `https://brainx.chaobrain.com/braintools/apis/braintools.html`
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
- # Braintools metrics
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 | Set `reduction` rather than assuming a scalar result. |
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 | Pass the sample interval as `dt`, not sampling frequency as `fs`. |
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. Validate every label yourself. |
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(...)` | Compare probability distributions. |
38
- | `kl_divergence_with_log_targets(...)` | Use when predictions and targets are already in log space. |
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
- **Critical exception:** JAX gather silently clamps out-of-range integer labels
63
- in `softmax_cross_entropy_with_integer_labels`. Validate
64
- `0 <= labels < logits.shape[-1]`; the function does not raise for invalid
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` or another supported reduction explicitly when a scalar is required. |
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(...)` | Use for mean absolute-error behavior according to its axis/reduction options. |
74
- | `l2_loss(...)` | Use for squared L2 loss. |
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(voltages)` | Estimate synchrony from population voltage variance. |
94
- | `matrix_correlation(a, b)` | Correlate upper-triangular entries of two square matrices. |
95
- | `weighted_correlation(x, y, weights)` | Compute weighted Pearson correlation for two one-dimensional series. |
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)` | Compare sliding-window connectivity matrices to produce functional-connectivity dynamics. |
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
- | `raster_plot(spikes, times)` | Extract neuron indices and spike times from a dense spike matrix; this is a metric/data helper, not the visualization API. |
104
- | `firing_rate(spikes, width, dt=None)` | Average across neurons and smooth population rate with a rectangular window of physical width. |
105
- | `victor_purpura_distance(spike_times_1, spike_times_2, cost_factor=1.0)` | Measure edit cost from insertions, deletions, and temporal shifts. |
106
- | `van_rossum_distance(spike_times_1, spike_times_2, tau=...)` | Compare exponentially filtered spike trains. |
107
- | `spike_train_synchrony(spikes, window_size, dt=None)` | Compute SPIKE-style synchronization on a population matrix. |
108
- | `burst_synchrony_index(spikes, dt=None, ...)` | Measure co-occurring burst events. |
109
- | `phase_locking_value(spikes, reference_freq, dt=None, ...)` | Measure spike phase locking to a reference oscillation. |
110
- | `spike_time_tiling_coefficient(spikes, dt=None, tau=...)` | Compute STTC within a temporal tolerance. |
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
- from braintools.metric import firing_rate, spike_train_synchrony
121
+ import braintools
122
+ import jax.numpy as jnp
116
123
 
117
- # Shape: (num_time, num_neurons)
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, neuron_type, seed=None, ...)` | Construct unitary LFP contributions from spikes; use the documented `'exc'` or `'inh'` neuron type. |
134
- | `power_spectral_density(lfp, dt, nperseg=None, noverlap=None, freq_range=None)` | Return one-sided Welch frequencies and PSD. |
135
- | `coherence_analysis(signal1, signal2, dt, ...)` | Return frequency-resolved magnitude-squared coherence. |
136
- | `phase_amplitude_coupling(lfp, dt, phase_freq_range, amplitude_freq_range, ...)` | Return Tort modulation index plus phase-bin details. |
137
- | `theta_gamma_coupling(lfp, dt, ...)` | Return theta-gamma coupling using standard bands. |
138
- | `current_source_density(lfp, electrode_spacing, axis=0, ...)` | Estimate laminar CSD along the electrode axis. |
139
- | `spectral_entropy(lfp, dt, ...)` | Return normalized spectral entropy. |
140
- | `lfp_phase_coherence(lfp, dt, freq_band, ...)` | Compute pairwise phase coherence across channels. |
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 source
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
- - `https://brainx.chaobrain.com/braintools/apis/metric.html`
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
@@ -1,6 +1,6 @@
1
1
  # BrainMass model library
2
2
 
3
- Use this reference when selecting a public BrainMass model, comparing dynamical cost, identifying its primary observable, or distinguishing variants with similar names. Return to `skills/package-skills/brainmass/SKILL.md` after selection for the canonical `Simulator` workflow.
3
+ Use this reference when selecting a public BrainMass model, comparing dynamical cost, identifying its primary observable, or distinguishing variants with similar names. Return to `SKILL.md` after selection for the canonical `Simulator` workflow.
4
4
 
5
5
  ## Inspect the public catalogue
6
6
 
@@ -81,7 +81,9 @@ Match the intervention to the model's equations; similarly named inhibitory para
81
81
  | API | Description |
82
82
  |---|---|
83
83
  | `JansenRitStep(Ai=...)` | Use for inhibitory postsynaptic gain in an alpha/EEG cortical column; `Ai` is measured in mV and scales the inhibitory-population filter, so lowering it weakens the inhibitory postsynaptic potential represented in `eeg() = E - I`. |
84
- | `WilsonCowanStep(wEI=...)` | Use for inhibitory feedback onto the excitatory rate population; `wEI` is dimensionless I-to-E coupling and enters the excitatory equation subtractively, so lowering it weakens that coupling. |
84
+ | `WilsonCowanStep(wIE=...)` | Use for inhibitory feedback onto the excitatory population in BrainMass `0.1.1` (BrainX `2026.10.25`). Lower `wIE` to weaken the dimensionless, subtractive I→E coupling. `wEI` controls E→I in this release. |
85
+
86
+ Verify the keyword mapping with unequal cross weights before porting a Wilson–Cowan intervention. Compare both derivatives or a short integration step with the intended equations. The published equations and gallery use the opposite keyword convention.
85
87
 
86
88
  Change only the selected inhibitory parameter in a matched causal comparison. Treat defaults and source-documented estimation ranges as context, not as evidence for a chosen intervention magnitude. Label an unsourced, outcome-tuned, or outside-range value as phenomenological and show nearby sensitivity before claiming a robust regime change.
87
89
 
@@ -167,14 +169,14 @@ Open only the script that matches the selected model or scientific regime.
167
169
 
168
170
  | Script | Open when |
169
171
  |---|---|
170
- | `scripts/hopf-bifurcation-single-node.py` | Demonstrating oscillation onset across the Hopf bifurcation or checking settled amplitude against `sqrt(a)`. |
171
- | `scripts/wilson-cowan-ei-dynamics.py` | Simulating E/I population rates, their phase portrait, or an excitatory-drive sweep. |
172
- | `scripts/jansen-rit-eeg-proxy.py` | Simulating the Jansen-Rit EEG proxy, its spectrum, or an input-rate sweep. |
173
- | `scripts/seizure-epileptor-case-study.py` | Comparing healthy and seizure-like Epileptor regimes across epileptogenicity `x0`. |
174
- | `scripts/wong-wang-decision-making.py` | Running stochastic competing-population decisions or estimating a psychometric curve. |
175
- | `scripts/kuramoto-synchronization.py` | Measuring synchronization through the Kuramoto order parameter while varying coupling strength. |
176
- | `scripts/wong-wang-dmf-resting-state.py` | Inspecting resting excitatory rate and gating in the Wong-Wang excitatory-inhibitory dynamic mean-field model. |
177
- | `scripts/linear-baseline-node.py` | Checking integration against the analytical linear decay before diagnosing a more complex model. |
172
+ | `references/scripts/hopf-bifurcation-single-node.py` | Demonstrating oscillation onset across the Hopf bifurcation or checking settled amplitude against `sqrt(a)`. |
173
+ | `references/scripts/wilson-cowan-ei-dynamics.py` | Simulating E/I population rates, their phase portrait, or an excitatory-drive sweep. |
174
+ | `references/scripts/jansen-rit-eeg-proxy.py` | Simulating the Jansen-Rit EEG proxy, its spectrum, or an input-rate sweep. |
175
+ | `references/scripts/seizure-epileptor-case-study.py` | Comparing healthy and seizure-like Epileptor regimes across epileptogenicity `x0`. |
176
+ | `references/scripts/wong-wang-decision-making.py` | Running stochastic competing-population decisions or estimating a psychometric curve. |
177
+ | `references/scripts/kuramoto-synchronization.py` | Measuring synchronization through the Kuramoto order parameter while varying coupling strength. |
178
+ | `references/scripts/wong-wang-dmf-resting-state.py` | Inspecting resting excitatory rate and gating in the Wong-Wang excitatory-inhibitory dynamic mean-field model. |
179
+ | `references/scripts/linear-baseline-node.py` | Checking integration against the analytical linear decay before diagnosing a more complex model. |
178
180
 
179
181
  ## Common selection failures
180
182
 
@@ -4,6 +4,8 @@ https://brainx.chaobrain.com/brainmass/gallery/case_studies/resting_state_meg.ht
4
4
  Converted from the official notebook at upstream commit
5
5
  293eaeb8948474c645208b68c531b7cb5482d4fb. Notebook outputs are omitted and
6
6
  ``%matplotlib inline`` remains commented; code and Markdown cells are preserved.
7
+
8
+ Requires BrainTools 0.4.0 or newer for functional-connectivity analysis.
7
9
  """
8
10
 
9
11
  # %% tags=["remove-cell"]
@@ -11,7 +13,7 @@ Converted from the official notebook at upstream commit
11
13
  # %matplotlib inline
12
14
  import brainmass
13
15
  import brainstate
14
- import braintools
16
+ from braintools.analysis.population import functional_connectivity
15
17
  import brainunit as u
16
18
  import jax
17
19
  import jax.numpy as jnp
@@ -209,8 +211,8 @@ target_res = brainmass.Simulator(target_net, dt=0.1 * u.ms).run(
209
211
  target_activity = target_res['output']
210
212
 
211
213
  # --- Functional connectivity: simulated vs target ---
212
- fc_sim = braintools.metric.functional_connectivity(u.get_magnitude(activity))
213
- fc_tar = braintools.metric.functional_connectivity(u.get_magnitude(target_activity))
214
+ fc_sim = functional_connectivity(u.get_magnitude(activity))
215
+ fc_tar = functional_connectivity(u.get_magnitude(target_activity))
214
216
 
215
217
  # (1) Structure-function coupling: does the simulated FC reflect the connectome?
216
218
  triu = np.triu_indices(N, k=1)
@@ -1,9 +1,9 @@
1
- """Reference script mirrored from:
1
+ """Reference script adapted from:
2
2
  https://brainx.chaobrain.com/brainmass/gallery/model_zoo/wilson_cowan.html
3
3
 
4
4
  Converted from the official notebook at upstream commit
5
- 293eaeb8948474c645208b68c531b7cb5482d4fb. Notebook outputs are omitted and
6
- ``%matplotlib inline`` remains commented; code and Markdown cells are preserved.
5
+ 293eaeb8948474c645208b68c531b7cb5482d4fb. The cross-population weights use
6
+ BrainMass 0.1.1 keyword names while preserving the notebook's directional gains.
7
7
  """
8
8
 
9
9
  # %% tags=["remove-cell"]
@@ -22,7 +22,11 @@ brainstate.environ.set(dt=0.1 * u.ms)
22
22
  #
23
23
  # The **Wilson-Cowan model** describes the coupled dynamics of an excitatory population rate $r_E$ and an inhibitory population rate $r_I$ through sigmoidal firing-rate functions:
24
24
  #
25
- # $$\tau_E\dot r_E = -r_E + S_E(w_{EE} r_E - w_{EI} r_I + I_E),\qquad \tau_I\dot r_I = -r_I + S_I(w_{IE} r_E - w_{II} r_I + I_I).$$
25
+ # $$\tau_E\dot r_E = -r_E + (1-r\,r_E) S_E(w_{EE} r_E - w_{IE} r_I + I_E),$$
26
+ # $$\tau_I\dot r_I = -r_I + (1-r\,r_I) S_I(w_{EI} r_E - w_{II} r_I + I_I).$$
27
+ #
28
+ # In BrainMass 0.1.1, WilsonCowanStep uses source-to-target subscripts.
29
+ # Its refractory coefficient r defaults to 1.
26
30
  #
27
31
  # Depending on the synaptic weights and inputs the model exhibits a stable low-activity state, multistability, or sustained oscillations from the excitatory-inhibitory loop. It is the classic two-population mean-field model of cortical dynamics.
28
32
  #
@@ -36,7 +40,7 @@ brainstate.environ.set(dt=0.1 * u.ms)
36
40
  # %%
37
41
  node = brainmass.WilsonCowanStep(
38
42
  in_size=1, tau_E=2.5 * u.ms, tau_I=3.75 * u.ms,
39
- wEE=16.0, wEI=12.0, wIE=15.0, wII=3.0)
43
+ wEE=16.0, wEI=15.0, wIE=12.0, wII=3.0)
40
44
  node
41
45
 
42
46
  # %% [markdown]
@@ -75,7 +79,7 @@ fig, ax = plt.subplots(figsize=(8, 4))
75
79
  for drive in [0.0, 1.0, 2.5]:
76
80
  m = brainmass.WilsonCowanStep(
77
81
  in_size=1, tau_E=2.5 * u.ms, tau_I=3.75 * u.ms,
78
- wEE=16.0, wEI=12.0, wIE=15.0, wII=3.0)
82
+ wEE=16.0, wEI=15.0, wIE=12.0, wII=3.0)
79
83
  r = brainmass.Simulator(m, dt=0.1 * u.ms).run(
80
84
  300. * u.ms, inputs=lambda i, t, d=drive: (d, 0.0),
81
85
  monitors=['rE'], transient=50. * u.ms)
@@ -8,9 +8,11 @@ Use this reference when a BrainMass run needs driven inputs, custom observables,
8
8
 
9
9
  | API | Description |
10
10
  |---|---|
11
- | `brainmass.Simulator(model, dt=...)` | Use to bind a model or `Network` to an integration step for the standard run path. |
11
+ | `brainmass.Simulator(model, dt=...)` | Use to bind any `brainstate.nn.Module` model or `Network` to an integration step for the standard run path. |
12
12
  | `Simulator.run(duration, *, inputs=None, monitors=None, transient=None, sample_every=None, batch_size=None, init_states=True, jit=True)` | Use to execute a duration and return a dict of time-major monitored values plus unit-aware `ts`. It initializes State and JIT-compiles by default. |
13
13
 
14
+ `model` may be any `brainstate.nn.Module`, including a custom aggregate model you define. A model missing from the public catalogue does not justify rebuilding the initializer, time loop, or monitors.
15
+
14
16
  Do not manually derive the number of steps, initialize State, scope `dt`, build a transformed loop, downsample, or reconstruct timestamps when these controls express the run.
15
17
 
16
18
  ## Supply model inputs
@@ -1,6 +1,6 @@
1
1
  # Visualization and analysis
2
2
 
3
- Use this reference when plotting BrainMass results or computing time-series, functional-connectivity, functional-connectivity-dynamics, and spectral summaries. Keep scientific metric computation in Braintools and use `brainmass.viz` as the thin optional plotting layer.
3
+ Use this reference when plotting BrainMass results or computing sample-by-signal Pearson similarity, time-series, functional-connectivity, functional-connectivity-dynamics, and spectral summaries. Keep scientific metric computation in Braintools and use `brainmass.viz` as the thin optional plotting layer.
4
4
 
5
5
  ## Plot results
6
6
 
@@ -18,16 +18,23 @@ Every helper accepts `ax=` and returns the `matplotlib.axes.Axes` it drew on. Pa
18
18
 
19
19
  ## Compute standard summaries
20
20
 
21
+ The FC, FCD, and PSD examples require BrainTools 0.4.0 or newer and use
22
+ `braintools.analysis`.
23
+
21
24
  Strip units explicitly before a metric that operates on scale-free raw arrays. Keep the sampling interval and labels separately.
22
25
 
23
26
  | API | Description |
24
27
  |---|---|
25
- | `braintools.metric.functional_connectivity(signal)` | Compute pairwise correlation across regions from a `(time, regions)` trajectory. |
26
- | `braintools.metric.functional_connectivity_dynamics(signal, window_size, step_size)` | Slide an FC window and correlate windowed FC matrices to return an `(n_window, n_window)` FCD matrix. |
27
- | `braintools.metric.power_spectral_density(signal, dt, nperseg=None, noverlap=None, freq_range=None)` | Use for a one-sided Welch PSD of a `(time,)` or `(time, channels)` signal; pass `dt` as a time `Quantity` or a float in seconds, and it returns frequencies in Hz plus PSD shaped `(frequency,)` or `(frequency, channels)`. |
28
+ | `braintools.analysis.population.functional_connectivity(activities)` | Compute the square pairwise Pearson matrix across columns of a `(time, signals)` array; check axes and undefined values before use. |
29
+ | `braintools.analysis.population.functional_connectivity_dynamics(activities, window_size=30, step_size=5)` | Correlate windowed FC matrices to return an `(n_window, n_window)` FCD matrix; specify the window and step in recorded samples. |
30
+ | `braintools.analysis.spectral.power_spectral_density(lfp, dt, nperseg=None, noverlap=None, freq_range=None)` | Use for a one-sided Welch PSD of a `(time,)` or `(time, channels)` signal; pass `dt` as a time `Quantity` or a float in seconds, and it returns frequencies in Hz plus PSD shaped `(frequency,)` or `(frequency, channels)`. |
28
31
  | `brainmass.objectives.fc_corr()` | Score correlation between prediction and target FC without manually recomputing the comparison logic. |
29
32
  | `brainmass.objectives.fcd_distribution(fcd_matrix, ...)` | Estimate the off-diagonal FCD value distribution used by distributional FCD objectives. |
30
33
 
34
+ For columnwise Pearson similarity over other observations, such as stimulus responses, evaluate this same API before writing a generic correlation implementation. This extends the documented time-series layout algebraically: verify the required centering, precision and reduction axis, and label the result by its actual observable rather than implying temporal or causal connectivity. A host-side data-generation boundary does not by itself exclude an applicable BrainTools metric.
35
+
36
+ Check finite inputs and positive column variances before correlation when undefined Pearson values must remain undefined. In BrainTools 0.4.0, a constant column returned zeros off the diagonal and one on the diagonal in a CPU probe. Reject invalid columns or preserve an explicit validity mask under the scientific missing-value policy. Verify parity on a small witness before substituting the API into a source-defined analysis. See the [official Pearson matrix contract](https://brainx.chaobrain.com/braintools/apis/generated/braintools.analysis.population.functional_connectivity.html) for shapes and NaN handling.
37
+
31
38
  ## Canonical analysis workflow
32
39
 
33
40
  ```python
@@ -70,8 +77,8 @@ result = brainmass.Simulator(network, dt=dt).run(
70
77
  )
71
78
 
72
79
  signal = u.get_magnitude(result["output"])
73
- fc = braintools.metric.functional_connectivity(signal)
74
- fcd = braintools.metric.functional_connectivity_dynamics(
80
+ fc = braintools.analysis.population.functional_connectivity(signal)
81
+ fcd = braintools.analysis.population.functional_connectivity_dynamics(
75
82
  signal,
76
83
  window_size=100,
77
84
  step_size=20,
@@ -104,7 +111,7 @@ Use one channel at a time unless the metric explicitly accepts multichannel inpu
104
111
 
105
112
  ```python
106
113
  record_dt = result["ts"][1] - result["ts"][0]
107
- frequencies, power = braintools.metric.power_spectral_density(
114
+ frequencies, power = braintools.analysis.spectral.power_spectral_density(
108
115
  signal[:, 0],
109
116
  record_dt,
110
117
  )
@@ -126,5 +133,6 @@ Freeze a signal-amplitude or in-band-power floor before inspecting condition out
126
133
 
127
134
  ## Official sources
128
135
 
129
- - `https://brainx.chaobrain.com/brainmass/reference/viz.html`
130
- - `https://brainx.chaobrain.com/brainmass/howto/analyze_results.html`
136
+ - [BrainTools analysis API](https://brainx.chaobrain.com/braintools/apis/analysis.html)
137
+ - [BrainMass visualization API](https://brainx.chaobrain.com/brainmass/reference/viz.html)
138
+ - [BrainMass results analysis guide](https://brainx.chaobrain.com/brainmass/howto/analyze_results.html)