brainx-skill 1.0.6 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +10 -8
  2. package/adapters/gemini.js +7 -0
  3. package/adapters/opencode.js +7 -0
  4. package/adapters/windsurf.js +7 -0
  5. package/installation/lib/installer.js +4 -1
  6. package/manifest.json +6 -1
  7. package/package.json +8 -2
  8. package/skills/braincell/SKILL.md +182 -0
  9. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  10. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +273 -0
  11. package/skills/braincell/references/channel-library.md +85 -0
  12. package/skills/braincell/references/ion-library.md +87 -0
  13. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  14. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  15. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  16. package/skills/braincell/references/multicompartment/filter-function-library.md +154 -0
  17. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  18. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  19. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  20. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +260 -0
  21. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  22. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  23. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  24. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  25. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  26. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  27. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  28. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  29. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  30. package/skills/brainevent/SKILL.md +268 -0
  31. package/skills/brainevent/references/connectivity-variants.md +312 -0
  32. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  33. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  34. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  35. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  36. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  37. package/skills/brainevent/references/sparse-formats.md +182 -0
  38. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  39. package/skills/brainmass/SKILL.md +290 -0
  40. package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
  41. package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
  42. package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  43. package/skills/brainmass/references/braintools/cogtask.md +190 -0
  44. package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
  45. package/skills/brainmass/references/braintools/metric.md +157 -0
  46. package/skills/brainmass/references/braintools/optimizer.md +187 -0
  47. package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
  48. package/skills/brainmass/references/braintools/surrogate.md +151 -0
  49. package/skills/brainmass/references/coupling-network-api.md +148 -0
  50. package/skills/brainmass/references/datasets-api.md +72 -0
  51. package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
  52. package/skills/brainmass/references/forward-observation-api.md +131 -0
  53. package/skills/brainmass/references/horn-task-training.md +199 -0
  54. package/skills/brainmass/references/modellibrary.md +104 -0
  55. package/skills/brainmass/references/noiseprocesses.md +121 -0
  56. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
  57. package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
  58. package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
  59. package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
  60. package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
  61. package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
  62. package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
  63. package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
  64. package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
  65. package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
  66. package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
  67. package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
  68. package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
  69. package/skills/brainmass/references/visualization-analysis-api.md +130 -0
  70. package/skills/brainpy-state/SKILL.md +232 -0
  71. package/skills/brainpy-state/references/array-creation.md +158 -0
  72. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  73. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  75. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  76. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  77. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  78. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  79. package/skills/brainpy-state/references/component-selection.md +273 -0
  80. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  81. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  82. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  83. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  84. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  85. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  86. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  87. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  88. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  89. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  90. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  91. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  92. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  93. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  94. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  95. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  96. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  97. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  98. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  99. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  100. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  101. package/skills/brainstate/SKILL.md +1 -1
  102. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
  103. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
  104. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
  105. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
  106. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
  107. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
  108. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
  109. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
  110. package/skills/brainstate/references/collective_model_operations.md +9 -9
  111. package/skills/brainstate/references/extension_mechanisms.md +12 -1
  112. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
  113. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
  114. package/skills/brainstate/references/model-interop-and-migration.md +11 -1
  115. package/skills/brainstate/references/size-inference-variations.md +11 -0
  116. package/skills/brainstate/references/state-graph-operations.md +13 -15
  117. package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
  118. package/skills/brainx-general-guard/SKILL.md +68 -0
  119. package/skills/brainstate/references/braintools-optimizer-reference.md +0 -133
  120. package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
@@ -0,0 +1,72 @@
1
+ """Reference script mirrored from:
2
+ https://brainx.chaobrain.com/brainmass/gallery/model_zoo/wong_wang_exc_inh.html
3
+
4
+ Converted from the official notebook at upstream commit
5
+ 293eaeb8948474c645208b68c531b7cb5482d4fb. Notebook outputs are omitted and
6
+ ``%matplotlib inline`` remains commented; code and Markdown cells are preserved.
7
+ """
8
+
9
+ # %% tags=["remove-cell"]
10
+ # %matplotlib inline
11
+ import brainmass
12
+ import brainstate
13
+ import brainunit as u
14
+ import jax.numpy as jnp
15
+ import numpy as np
16
+ import matplotlib.pyplot as plt
17
+ brainstate.random.seed(0)
18
+ brainstate.environ.set(dt=0.1 * u.ms)
19
+
20
+ # %% [markdown]
21
+ # # Wong-Wang Excitatory-Inhibitory (Dynamic Mean Field)
22
+ #
23
+ # The **two-population (excitatory-inhibitory) reduced Wong-Wang model**, often called the *dynamic mean field* (DMF), is the resting-state workhorse for whole-brain modeling. Each region has an excitatory NMDA gating variable $S_E$ and an inhibitory GABA gating variable $S_I$; a feedback-inhibition weight $J_i$ regulates the local excitation-inhibition balance so that the excitatory population settles near a biologically plausible ~3 Hz resting rate. It is the node model behind much resting-state BOLD / functional-connectivity work.
24
+ #
25
+ # *(Distinct from the reduced two-choice* `WongWangStep` *decision model.)*
26
+ #
27
+ # **Reference:** Deco, Ponce-Alvarez, Hagmann, Romani, Mantini & Corbetta (2014), *How local excitation-inhibition ratio impacts the whole brain dynamics*, Journal of Neuroscience 34(23):7886-7898.
28
+
29
+ # %% [markdown]
30
+ # ## Build the model
31
+
32
+ # %%
33
+ node = brainmass.WongWangExcInhStep(in_size=1, J_i=1.0, G=2.0)
34
+ node
35
+
36
+ # %% [markdown]
37
+ # ## Run a simulation
38
+ #
39
+ # We monitor the excitatory gating variable `S_e` and the derived excitatory firing rate via the `H_e()` observable.
40
+
41
+ # %%
42
+ sim = brainmass.Simulator(node, dt=0.1 * u.ms)
43
+ res = sim.run(3000. * u.ms,
44
+ monitors={'S_e': 'S_e', 'rate_e': lambda m: m.H_e()})
45
+ float(u.get_magnitude(res['rate_e'])[-1, 0]) # resting excitatory rate (Hz)
46
+
47
+ # %% [markdown]
48
+ # ## Visualize
49
+ #
50
+ # The gating variable settles to a steady value and the excitatory rate stabilizes near the ~3 Hz resting fixed point.
51
+
52
+ # %%
53
+ fig, axes = plt.subplots(1, 2, figsize=(11, 4))
54
+ brainmass.viz.plot_timeseries(res['S_e'], ts=res['ts'], ax=axes[0])
55
+ axes[0].set_title('Excitatory gating S_e')
56
+ brainmass.viz.plot_timeseries(res['rate_e'], ts=res['ts'], ax=axes[1])
57
+ axes[1].set_title('Excitatory rate H_e (Hz)')
58
+ plt.tight_layout()
59
+ plt.show()
60
+
61
+ # %% [markdown]
62
+ # ## Try it: vary the feedback inhibition `J_i`
63
+ #
64
+ # The feedback-inhibition weight `J_i` sets the E-I balance. Stronger inhibition clamps the excitatory rate lower; weaker inhibition lets it climb. We report the settled excitatory rate.
65
+
66
+ # %%
67
+ for J_i in [0.5, 1.0, 1.5]:
68
+ m = brainmass.WongWangExcInhStep(in_size=1, J_i=J_i, G=2.0)
69
+ r = brainmass.Simulator(m, dt=0.1 * u.ms).run(
70
+ 3000. * u.ms, monitors={'rate_e': lambda m: m.H_e()})
71
+ rate = float(u.get_magnitude(r['rate_e'])[-1, 0])
72
+ print(f'J_i = {J_i:.1f} -> resting excitatory rate = {rate:.2f} Hz')
@@ -0,0 +1,130 @@
1
+ # Visualization and analysis
2
+
3
+ Use this reference when plotting BrainMass results or computing time-series, functional-connectivity, functional-connectivity-dynamics, and spectral summaries. Keep scientific metric computation in Braintools and use `brainmass.viz` as the thin optional plotting layer.
4
+
5
+ ## Plot results
6
+
7
+ `brainmass.viz` imports matplotlib lazily. Install the BrainMass visualization extra before using it; core `brainmass` imports do not require matplotlib.
8
+
9
+ | API | Description |
10
+ |---|---|
11
+ | `brainmass.viz.plot_timeseries(signal, ts=None, labels=None, ax=None, ...)` | Plot one or more time-major regional or sensor trajectories; it accepts unit-aware signal and time inputs. |
12
+ | `brainmass.viz.plot_phase_portrait(x, y, ax=None, ...)` | Plot one State variable against another for oscillator or attractor inspection. |
13
+ | `brainmass.viz.plot_connectivity(matrix, labels=None, ax=None, ...)` | Plot any square structural, functional, FCD, or regime matrix as a heatmap. |
14
+ | `brainmass.viz.plot_functional_connectivity(data, is_matrix=False, labels=None, ax=None, ...)` | Compute FC from a trajectory or plot an existing matrix when `is_matrix=True`. |
15
+ | `brainmass.viz.plot_power_spectrum(signal, dt, ax=None, loglog=False, ...)` | Compute and plot the PSD of one one-dimensional signal with sampling interval `dt`. |
16
+
17
+ Every helper accepts `ax=` and returns the `matplotlib.axes.Axes` it drew on. Pass axes explicitly when composing figures.
18
+
19
+ ## Compute standard summaries
20
+
21
+ Strip units explicitly before a metric that operates on scale-free raw arrays. Keep the sampling interval and labels separately.
22
+
23
+ | API | Description |
24
+ |---|---|
25
+ | `braintools.metric.functional_connectivity(signal)` | Compute pairwise correlation across regions from a `(time, regions)` trajectory. |
26
+ | `braintools.metric.functional_connectivity_dynamics(signal, window_size, step_size)` | Slide an FC window and correlate windowed FC matrices to return an `(n_window, n_window)` FCD matrix. |
27
+ | `braintools.metric.power_spectral_density(signal, dt_ms)` | Return frequencies and PSD for a one-dimensional signal; use a sampling interval in the expected raw unit. |
28
+ | `brainmass.objectives.fc_corr()` | Score correlation between prediction and target FC without manually recomputing the comparison logic. |
29
+ | `brainmass.objectives.fcd_distribution(fcd_matrix, ...)` | Estimate the off-diagonal FCD value distribution used by distributional FCD objectives. |
30
+
31
+ ## Canonical analysis workflow
32
+
33
+ ```python
34
+ import brainmass
35
+ import brainstate
36
+ import brainunit as u
37
+ import braintools
38
+ import numpy as np
39
+
40
+ dt = 0.1 * u.ms
41
+ brainstate.environ.set(dt=dt)
42
+ brainstate.random.seed(0)
43
+
44
+ connectome = brainmass.datasets.load_dataset("example_connectome")
45
+ n_region = connectome.weights.shape[0]
46
+ node = brainmass.HopfStep(
47
+ in_size=n_region,
48
+ a=0.1,
49
+ w=0.3,
50
+ noise_x=brainmass.OUProcess(
51
+ n_region,
52
+ sigma=0.1,
53
+ tau=10.0 * u.ms,
54
+ ),
55
+ )
56
+ network = brainmass.Network(
57
+ node,
58
+ conn=connectome.weights,
59
+ distance=connectome.distances,
60
+ speed=10.0 * u.mm / u.ms,
61
+ coupling="diffusive",
62
+ coupled_var="x",
63
+ k=0.5,
64
+ )
65
+ result = brainmass.Simulator(network, dt=dt).run(
66
+ 4000.0 * u.ms,
67
+ monitors=lambda model: model.node.x.value,
68
+ transient=400.0 * u.ms,
69
+ sample_every=10,
70
+ )
71
+
72
+ signal = u.get_magnitude(result["output"])
73
+ fc = braintools.metric.functional_connectivity(signal)
74
+ fcd = braintools.metric.functional_connectivity_dynamics(
75
+ signal,
76
+ window_size=100,
77
+ step_size=20,
78
+ )
79
+
80
+ assert fc.shape == (n_region, n_region)
81
+ assert fcd.ndim == 2 and fcd.shape[0] == fcd.shape[1]
82
+ ```
83
+
84
+ `sample_every=10` records every 1 ms when `dt=0.1 ms`; use the recorded `ts` difference as the analysis sampling interval rather than the integration `dt`.
85
+
86
+ ## Compare with data
87
+
88
+ Use the same preprocessing, region order, duration policy, and sampling rate before comparing summaries.
89
+
90
+ ```python
91
+ target = brainmass.datasets.load_dataset("example_signal")
92
+ score = brainmass.objectives.fc_corr()(
93
+ signal,
94
+ target.signal,
95
+ )
96
+ assert np.isfinite(float(score))
97
+ ```
98
+
99
+ Use `as_loss=True` only when the score is passed to a minimizer. A high FC score does not validate spectra, FCD, amplitudes, or parameter plausibility.
100
+
101
+ ## Analyze spectra
102
+
103
+ Use one channel at a time unless the metric explicitly accepts multichannel input.
104
+
105
+ ```python
106
+ record_dt_ms = float(
107
+ (result["ts"][1] - result["ts"][0]).to(u.ms).mantissa
108
+ )
109
+ frequencies, power = braintools.metric.power_spectral_density(
110
+ signal[:, 0],
111
+ record_dt_ms,
112
+ )
113
+ assert frequencies.shape == power.shape
114
+ ```
115
+
116
+ Convert cycles per millisecond to hertz only when the metric's returned frequency convention requires it. Do not infer a sampling frequency from the number of samples alone.
117
+
118
+ ## Common failures
119
+
120
+ - Computing FC over the region axis instead of the time axis.
121
+ - Comparing matrices whose region labels are in different orders.
122
+ - Using integration `dt` after `sample_every` changed the recorded sampling interval.
123
+ - Treating FCD as static FC or fitting the full matrix when the intended target is its off-diagonal distribution.
124
+ - Plotting a unit-bearing `Quantity` by implicit NumPy conversion instead of using `brainmass.viz` or `u.get_magnitude`.
125
+ - Claiming scientific validation from a single summary.
126
+
127
+ ## Official sources
128
+
129
+ - `https://brainx.chaobrain.com/brainmass/reference/viz.html`
130
+ - `https://brainx.chaobrain.com/brainmass/howto/analyze_results.html`
@@ -0,0 +1,232 @@
1
+ ---
2
+ name: brainpy-state
3
+ description: Use for point-neuron modeling, from individual neurons to spiking networks with synapses and projections. Use alone for point-neuron studies or together with BrainCell and/or BrainMass when point-neuron dynamics participate in a multiscale model.
4
+ ---
5
+
6
+ # BrainPy-State
7
+
8
+ ## Purpose and boundary
9
+
10
+ Use this skill for the native `brainpy.state` modeling path: compose point neurons, synapses, communication operators, synaptic outputs, projections, inputs, plasticity, and readouts into simulations or trainable spiking neural networks.
11
+
12
+ Route NEST-compatible work to `references/nest-compatible/nest-workflow.md`, and online-learning execution to BrainTrace.
13
+
14
+ ## Underlying principle of BrainPy-State
15
+
16
+ BrainPy-State composes unit-aware, stateful neuron and synapse `Dynamics` into projections that separate `comm`, `syn`, `out`, and `post`; BrainState transforms run the same Module graph for simulation or surrogate-gradient training.
17
+ Align synaptic State to a neuron dimension instead of each connection, reduce that state from per-synapse to per-neuron, which makes simulation memory-efficient.
18
+
19
+ ### API structure
20
+
21
+ | API family | Use |
22
+ |---|---|
23
+ | Base Classes | Find the shared dynamics, neuron, and synapse abstractions used to implement custom BrainPy-State components. |
24
+ | BrainPy-style Neurons | Select native point-neuron dynamics, from integrate-and-fire models to conductance-based models. |
25
+ | BrainPy-style Synapses | Select native synaptic dynamics, from simple temporal filters to biological receptor models. |
26
+ | BrainPy-style Projections | Connect populations through projection classes, projection helper functions, or gap-junction projections. |
27
+ | BrainPy-style Synaptic Outputs | Convert synaptic state into current- or conductance-based postsynaptic input. |
28
+ | BrainPy-style Plasticity | Add short-term facilitation or depression to synaptic transmission. |
29
+ | BrainPy-style Readouts | Decode spiking activity through native readout models. |
30
+ | BrainPy-style Input Generators | Generate spike trains or time-varying simulation inputs. |
31
+
32
+ ### 1. Choose and run neuron dynamics
33
+
34
+ A neuron call advances one `dt`, mutates its registered dynamical State, and exposes the current spike through `get_spike()`; initialize before every independent rollout and lower the complete time loop through `brainstate.transform`.
35
+
36
+ | API | Description |
37
+ |---|---|
38
+ | `brainpy.state.LIFRef(...)` | Use for the canonical point-neuron rollout when leak and refractory timing are required; each call integrates one `dt`, updates membrane/refractory State, and returns the current spike. |
39
+ | `brainstate.nn.init_all_states(model, batch_size=...)` | Use after construction and before a rollout; it allocates or resets dynamical State across the Module graph and adds a leading batch dimension when `batch_size` is given. |
40
+ | `brainstate.environ.context(dt=..., t=...)` | Use around the rollout for `dt` and inside the step for `t`; dynamics read the active values and the context restores previous settings on exit. |
41
+ | `brainstate.environ.get_dt()` | Use when constructing the time axis or a numerical update from the active simulation step; it returns `dt` and raises when no value is set. |
42
+ | `u.math.mean(current, axis=...)` | Use when a drive current should be the arithmetic mean of unit-aware samples; it reduces the selected axes and returns a quantity with the input current unit. |
43
+ | `brainstate.transform.for_loop(step, *xs)` | Use by default for a multi-step rollout whose model State carries hidden variables; it slices leading input axes and stacks returned monitors. |
44
+ | `neuron.get_spike()` | Use after advancing or when wiring the previous completed step into a projection; it returns the neuron's current spike output without advancing State. |
45
+
46
+ ```python
47
+ import brainpy
48
+ import brainstate
49
+ import brainunit as u
50
+
51
+ with brainstate.environ.context(dt=0.1 * u.ms):
52
+ neuron = brainpy.state.LIFRef(
53
+ 1,
54
+ R=1.0 * u.ohm,
55
+ tau=20.0 * u.ms,
56
+ V_rest=-60.0 * u.mV,
57
+ V_th=-50.0 * u.mV,
58
+ V_reset=-60.0 * u.mV,
59
+ tau_ref=5.0 * u.ms,
60
+ )
61
+ brainstate.nn.init_all_states(neuron)
62
+ times = u.math.arange(
63
+ 0.0 * u.ms,
64
+ 200.0 * u.ms,
65
+ brainstate.environ.get_dt(),
66
+ )
67
+
68
+ def step(t):
69
+ with brainstate.environ.context(t=t):
70
+ neuron(25.0 * u.mA)
71
+ return neuron.V.value, neuron.get_spike()
72
+
73
+ voltages, spikes = brainstate.transform.for_loop(step, times)
74
+
75
+ assert voltages.shape == (2000, 1)
76
+ assert spikes.shape == (2000, 1)
77
+ ```
78
+
79
+ Open `references/array-creation.md` when constructing specialized unit-aware current ranges, grids, filled arrays, template-shaped arrays, or matrix patterns. Open `references/component-selection.md` when choosing among documented neuron, input, synapse, output, plasticity, or readout variants, for the decision boundary and complete category list. Open `references/braintools/brainstate-control-flow-patterns.md` when the rollout needs explicit carry, branching, or checkpointed control flow.
80
+
81
+ ### 2. Compose synapses and projections
82
+
83
+ A projection deposits current into `post` before the postsynaptic neuron integrates the step, while its alignment determines which neuron dimension owns synaptic State and which kinetics remain exact.
84
+
85
+ | API | Description |
86
+ |---|---|
87
+ | `brainstate.nn.EventFixedProb(...)` | Use for the canonical sparse binary-spike communication path; it maps presynaptic events to postsynaptic weighted input without materializing dense all-to-all activity. |
88
+ | `brainevent.BinaryArray(spikes) @ connectivity` | Use when the network must choose an explicit BrainEvent connectivity representation; it processes active presynaptic events through dense, CSR, generated, or fixed-degree storage and returns input for BrainPy synaptic dynamics. |
89
+ | `brainpy.state.Expon.desc(...)` | Use for the canonical linear exponential synaptic filter; the descriptor lets the projection construct and align the concrete synapse on the target. |
90
+ | `brainpy.state.COBA.desc(E=...)` | Use when synaptic current must depend on postsynaptic voltage and reversal potential; the descriptor lets the projection bind the output to `post`. |
91
+ | `brainpy.state.AlignPostProj(...)` | Use for exponential-family fan-in; it composes `comm`, `syn`, `out`, and `post`, stores exact synaptic State on the postsynaptic dimension, and deposits current before `post(...)` integrates. |
92
+ | `brainpy.state.align_pre_projection(...)` | Use instead for nonlinear synaptic kinetics or reusable one-to-many fan-out; it stores exact shared traces on the presynaptic dimension when outgoing parameters are homogeneous per source. |
93
+
94
+ ```python
95
+ import brainpy
96
+ import brainstate
97
+ import brainunit as u
98
+
99
+
100
+ class TwoPop(brainstate.nn.Module):
101
+ def __init__(self, n_pre=20, n_post=10):
102
+ super().__init__()
103
+ self.pre = brainpy.state.LIFRef(
104
+ n_pre,
105
+ tau=20.0 * u.ms,
106
+ tau_ref=5.0 * u.ms,
107
+ V_rest=-60.0 * u.mV,
108
+ V_th=-50.0 * u.mV,
109
+ V_reset=-60.0 * u.mV,
110
+ )
111
+ self.post = brainpy.state.LIFRef(
112
+ n_post,
113
+ tau=20.0 * u.ms,
114
+ tau_ref=5.0 * u.ms,
115
+ V_rest=-60.0 * u.mV,
116
+ V_th=-50.0 * u.mV,
117
+ V_reset=-60.0 * u.mV,
118
+ )
119
+ self.proj = brainpy.state.AlignPostProj(
120
+ comm=brainstate.nn.EventFixedProb(
121
+ n_pre,
122
+ n_post,
123
+ conn_num=0.5,
124
+ conn_weight=0.5 * u.mS,
125
+ ),
126
+ syn=brainpy.state.Expon.desc(n_post, tau=5.0 * u.ms),
127
+ out=brainpy.state.COBA.desc(E=0.0 * u.mV),
128
+ post=self.post,
129
+ )
130
+
131
+ def update(self, t, drive):
132
+ with brainstate.environ.context(t=t):
133
+ pre_spikes = self.pre.get_spike() != 0.0
134
+ self.proj(pre_spikes)
135
+ self.pre(drive)
136
+ self.post(0.0 * u.mA)
137
+ return self.post.V.value, self.proj.syn.g.value
138
+
139
+
140
+ with brainstate.environ.context(dt=0.1 * u.ms):
141
+ net = TwoPop()
142
+ brainstate.nn.init_all_states(net)
143
+ times = u.math.arange(0.0 * u.ms, 200.0 * u.ms, brainstate.environ.get_dt())
144
+ post_voltage, conductance = brainstate.transform.for_loop(
145
+ lambda t: net.update(t, 30.0 * u.mA),
146
+ times,
147
+ )
148
+
149
+ assert post_voltage.shape == (2000, 10)
150
+ assert conductance.shape == (2000, 10)
151
+ ```
152
+
153
+ Open `references/projection-patterns.md` when selecting AlignPre versus either AlignPost API, adding short-term plasticity or delays, using direct/delta input, or composing electrical coupling. Open `skills/brainevent/references/scripts/coba_ei_teaching.py` when a BrainPy network should use BrainEvent for efficient event-driven communication; it keeps BrainPy neuron and synapse dynamics while replacing the communication step with `BinaryArray @ connectivity` over fixed-degree, CSR, or dense storage.
154
+
155
+ ### 3. Train a spiking network
156
+
157
+ Training reuses the simulation graph: place a surrogate on each trained spiking nonlinearity, unroll with a differentiable transform loop, differentiate only `ParamState`, reset dynamical State for each independent batch, and update inside a compiled train step.
158
+
159
+ | API | Description |
160
+ |---|---|
161
+ | `neuron(..., spk_fun=braintools.surrogate.ReluGrad())` | Use on a spiking layer crossed by the loss gradient; it preserves hard forward spikes and supplies the backward derivative. |
162
+ | `model.states(brainstate.ParamState)` | Use to select trainable parameters; it excludes membrane voltage, conductance, spike history, and other rollout State. |
163
+ | `brainstate.transform.grad(loss_fn, params, return_value=True)` | Use to differentiate the stateful loss with respect to the selected State collection; calling the returned transform yields gradients and the loss. |
164
+ | `braintools.optim.Adam(...).register_trainable_weights(params)` | Use for the canonical optimizer lifecycle; register the same State collection used by `grad`, then call `optimizer.update(grads)`. |
165
+ | `brainstate.transform.jit(train_step)` | Use around the complete reset-gradient-update operation; compatible calls reuse the compiled training step while BrainState preserves State effects. |
166
+
167
+ ```python
168
+ # Given a stateful net whose update() returns per-step logits [batch, classes].
169
+ params = net.states(brainstate.ParamState)
170
+ optimizer = braintools.optim.Adam(lr=3e-3)
171
+ optimizer.register_trainable_weights(params)
172
+
173
+ def loss_fn():
174
+ logits = brainstate.transform.for_loop(net.update, inputs)
175
+ logits = u.math.mean(logits, axis=0)
176
+ return braintools.metric.softmax_cross_entropy_with_integer_labels(
177
+ logits,
178
+ labels,
179
+ ).mean()
180
+
181
+ @brainstate.transform.jit
182
+ def train_step():
183
+ brainstate.nn.init_all_states(net, batch_size=batch_size)
184
+ grads, loss = brainstate.transform.grad(
185
+ loss_fn,
186
+ params,
187
+ return_value=True,
188
+ )()
189
+ optimizer.update(grads)
190
+ return loss
191
+
192
+ loss = train_step()
193
+ ```
194
+
195
+ Choose training variations from the first-level references below; open only the smallest reference that owns the decision. Use `references/scripts/training-snn.py` when a complete runnable training workflow is required.
196
+
197
+ ## Reference routing
198
+
199
+ Open only the smallest reference that owns the decision.
200
+
201
+ ### Training variation choices
202
+
203
+ | Reference | Open when |
204
+ |---|---|
205
+ | `references/braintools/data-preprocessing.md` | Encoding continuous values, events, or temporal features into time-major spike inputs before training |
206
+ | `references/braintools/parameter-initializer.md` | Selecting unit-aware parameter, weight, delay, variance-scaling, orthogonal, or spatial initialization |
207
+ | `references/braintools/surrogate.md` | Selecting a surrogate API style or gradient family, implementing a custom surrogate, or validating its gradient |
208
+ | `references/braintools/metric.md` | Selecting the training loss or evaluation metric and validating its input orientation, units, and reduction |
209
+ | `references/braintools/optimizer.md` | Selecting an optimizer, learning-rate scheduler, Optax bridge, SciPy optimizer, or Nevergrad optimizer |
210
+ | `references/braintools/brainstate-control-flow-patterns.md` | Choosing `for_loop` versus `scan`, adding transformed branches, or checkpointing a long differentiated rollout |
211
+
212
+ ### Modeling variation choices
213
+
214
+ | Reference | Open when |
215
+ |---|---|
216
+ | `references/array-creation.md` | Constructing specialized unit-aware current ranges, grids, filled arrays, template-shaped arrays, or matrix patterns |
217
+ | `references/component-selection.md` | Choosing a neuron, synapse, synaptic output, plasticity model, input generator, or readout from the documented native API families |
218
+ | `references/projection-patterns.md` | Choosing projection alignment or API form, adding delays or short-term plasticity, using direct/delta projections, or adding gap junctions |
219
+ | `references/nest-compatible/nest-workflow.md` | Using NEST/PyNEST model names, `Simulator`, devices, connection rules, spatial networks, parity, porting, or the bundled NEST-compatible full scripts |
220
+ | `skills/brainevent/SKILL.md` | Selecting sparse event representations, connectivity formats, event operators, plasticity kernels, or custom kernels |
221
+ | `skills/brainevent/references/scripts/coba_ei_teaching.py` | Learning how to incorporate efficient BrainEvent communication into a complete BrainPy COBA E/I network while preserving BrainPy dynamics and BrainState execution |
222
+
223
+
224
+ ## Application script examples
225
+ | Reference | Open when |
226
+ |---|---|
227
+ | `references/scripts/103_COBA_2005.py` | Needing a complete canonical E/I COBA network built from native BrainPy-State projections |
228
+ | `references/scripts/106_COBA_HH_2007.py` | Reproducing a conductance-based E/I network with a custom Hodgkin-Huxley neuron |
229
+ | `references/scripts/107_gamma_oscillation_1996.py` | Reproducing gamma oscillations with custom neuron and synapse dynamics |
230
+ | `references/scripts/109_fast_global_oscillation.py` | Needing a complete `DeltaProj` network with delayed recurrent input |
231
+ | `references/scripts/201_surrogate_grad_lif_fashion_mnist.py` | Needing a complete real-data surrogate-gradient LIF training workflow |
232
+ | `references/scripts/training-snn.py` | Needing a complete runnable surrogate-gradient SNN training workflow |
@@ -0,0 +1,158 @@
1
+ # Array creation
2
+
3
+ Use this reference for specialized unit-aware ranges, grids, filled arrays, template-shaped arrays, matrix patterns, index constructors, and tree-shaped arrays. Basic `Quantity`, `asarray()`, and `arange()` construction remains in the parent skill.
4
+
5
+ ```python
6
+ import brainunit as u
7
+ import jax.numpy as jnp
8
+ ```
9
+
10
+ ## Contents
11
+
12
+ - [Choose interval values](#choose-interval-values)
13
+ - [Build coordinate and power grids](#build-coordinate-and-power-grids)
14
+ - [Fill a new shape](#fill-a-new-shape)
15
+ - [Follow an existing shape](#follow-an-existing-shape)
16
+ - [Build matrices and masks](#build-matrices-and-masks)
17
+ - [Locate triangular entries](#locate-triangular-entries)
18
+ - [Mirror pytrees](#mirror-pytrees)
19
+ - [Convert NumPy input](#convert-numpy-input)
20
+ - [Routing](#routing)
21
+ - [Cross-family gotchas](#cross-family-gotchas)
22
+ - [Sources mirrored](#sources-mirrored)
23
+
24
+ ## Choose interval values
25
+
26
+ ### `linspace`
27
+
28
+ | Exact signature | Use when | One-line description | Code and result |
29
+ |---|---|---|---|
30
+ | `linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)` | Generate a fixed number of evenly spaced samples between two endpoints. | Return evenly spaced numbers over a specified interval. | `u.math.linspace(0 * u.second, 10 * u.second, 5)`<br>`# Quantity([ 0. 2.5 5. 7.5 10. ], "s")` |
31
+
32
+ ### `logspace`
33
+
34
+ | Exact signature | Use when | One-line description | Code and result |
35
+ |---|---|---|---|
36
+ | `logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)` | Generate values whose exponents are evenly spaced. | Return numbers spaced evenly on a log scale. | `u.math.logspace(0, 2, 3)`<br>`# Array([ 1., 10., 100.], dtype=float32)` |
37
+
38
+ ## Build coordinate and power grids
39
+
40
+ ### `meshgrid`
41
+
42
+ | Exact signature | Use when | One-line description | Code and result |
43
+ |---|---|---|---|
44
+ | `meshgrid(*xi, copy=True, sparse=False, indexing='xy')` | Expand 1-D coordinate vectors into dense or sparse coordinate grids. | Return coordinate matrices from coordinate vectors. | `x = jnp.array([1, 2]) * u.meter; t = jnp.array([0, 1, 2]) * u.second; x_grid, t_grid = u.math.meshgrid(x, t, indexing='ij')`<br>`# both shapes: (2, 3); units: meter and second` |
45
+
46
+ ### `vander`
47
+
48
+ | Exact signature | Use when | One-line description | Code and result |
49
+ |---|---|---|---|
50
+ | `vander(x, N=None, increasing=False, unit=Unit('1'))` | Build a Vandermonde matrix from powers of a 1-D vector. | Generate a Vandermonde matrix. | `u.math.vander(jnp.array([1, 2]), N=3)`<br>`# Array([[1, 1, 1], [4, 2, 1]], dtype=int32)` |
51
+
52
+ ## Fill a new shape
53
+
54
+ ### Initialized arrays
55
+
56
+ | API | Description & result |
57
+ |---|---|
58
+ | `full(shape, fill_value, dtype=None)` | Fill a new shape with `fill_value`; a quantity fill produces a `Quantity` with that unit.<br>`u.math.full(2, 3 * u.second)`<br>`# Quantity([3, 3], "s")` |
59
+ | `ones(shape, dtype=None, unit=Unit('1'))` | Fill a new shape with ones. Returns a plain JAX array by default or a `Quantity` when a non-trivial unit is supplied.<br>`u.math.ones(2, unit=u.second)`<br>`# Quantity([1., 1.], "s")` |
60
+ | `zeros(shape, dtype=None, unit=Unit('1'))` | Fill a new shape with zeros. Returns a plain JAX array by default or a `Quantity` when a non-trivial unit is supplied.<br>`u.math.zeros(2)`<br>`# plain JAX array` |
61
+
62
+ ### `empty`
63
+
64
+ | Exact signature | Use when | One-line description | Code and result |
65
+ |---|---|---|---|
66
+ | `empty(shape, dtype=None, unit=Unit('1'))` | Allocate a shape when every entry will be overwritten before it is read. | Return a new quantity or array of given shape and type, without initializing entries. | `buffer = u.math.empty((2, 2), unit=u.second); buffer.shape`<br>`# (2, 2); entry values are unspecified` |
67
+
68
+ ## Follow an existing shape
69
+
70
+ ### `full_like`
71
+
72
+ | Exact signature | Use when | One-line description | Code and result |
73
+ |---|---|---|---|
74
+ | `full_like(a, fill_value, dtype=None, shape=None)` | Fill an array using a prototype's shape and dtype. | Return a new quantity or array with the same shape and type as a given array or quantity, filled with `fill_value`. | `prototype = jnp.zeros(2) * u.second; u.math.full_like(prototype, 500 * u.ms)`<br>`# Quantity([0.5 0.5], "s")` |
75
+
76
+ ### `empty_like`
77
+
78
+ | Exact signature | Use when | One-line description | Code and result |
79
+ |---|---|---|---|
80
+ | `empty_like(prototype, dtype=None, shape=None, unit=Unit('1'))` | Allocate an uninitialized buffer shaped and typed like a prototype. | Return a new quantity or array with the same shape and type as a given array. | `prototype = jnp.ones(3) * u.second; buffer = u.math.empty_like(prototype); buffer.shape`<br>`# (3,); unit: second; entry values are unspecified` |
81
+
82
+ ### Create one or zero arrays
83
+
84
+ | API | Description & result |
85
+ |---|---|
86
+ | `ones_like(a, dtype=None, shape=None, unit=Unit('1'))` | Create ones with `a`'s shape and dtype. A `Quantity` prototype preserves its unit by default; a non-trivial `unit` attaches a unit to a plain prototype or requests a compatible conversion. |
87
+ | `zeros_like(a, dtype=None, shape=None, unit=Unit('1'))` | Create zeros with `a`'s shape and dtype. A `Quantity` prototype preserves its unit by default; a non-trivial `unit` attaches a unit to a plain prototype or requests a compatible conversion. |
88
+
89
+ ## Build matrices and masks
90
+
91
+ ### Identity-like and triangular constructors
92
+
93
+ | API | Description & result |
94
+ |---|---|
95
+ | `eye(N, M=None, k=0, dtype=None, unit=Unit('1'))` | Create an `N`-by-`M` array with ones on diagonal `k` and zeros elsewhere. Returns a plain JAX array by default or a `Quantity` with a non-trivial unit. |
96
+ | `identity(n, dtype=None, unit=Unit('1'))` | Create an `n`-by-`n` identity array. Returns a plain JAX array by default or a `Quantity` with a non-trivial unit. |
97
+ | `tri(N, M=None, k=0, dtype=None, unit=Unit('1'))` | Create an `N`-by-`M` array with ones at and below diagonal `k`. Returns a plain JAX array by default or a `Quantity` with a non-trivial unit. |
98
+
99
+ ### `diag`
100
+
101
+ | Exact signature | Use when | One-line description | Code and result |
102
+ |---|---|---|---|
103
+ | `diag(v, k=0, unit=Unit('1'))` | Construct a diagonal matrix or extract a diagonal based on input rank. | Extract a diagonal or construct a diagonal array. | `vector = jnp.array([1, 2, 3]) * u.second; matrix = u.math.diag(vector); extracted = u.math.diag(matrix); (matrix.shape, extracted.shape)`<br>`# ((3, 3), (3,))` |
104
+
105
+ ### Keep one triangle of an existing array
106
+
107
+ | API | Description & result |
108
+ |---|---|
109
+ | `tril(m, k=0, unit=Unit('1'))` | Return `m` with entries above diagonal `k` zeroed, applying to the final two axes when `m.ndim > 2`. It preserves a `Quantity` input's unit by default; `unit` can attach or request a compatible output unit.<br>`m = jnp.arange(1, 5).reshape(2, 2); u.math.tril(m)`<br>`# [[1, 0], [3, 4]]` |
110
+ | `triu(m, k=0, unit=Unit('1'))` | Return `m` with entries below diagonal `k` zeroed, applying to the final two axes when `m.ndim > 2`. It preserves a `Quantity` input's unit by default; `unit` can attach or request a compatible output unit.<br>`m = jnp.arange(1, 5).reshape(2, 2); u.math.triu(m)`<br>`# [[1, 2], [0, 4]]` |
111
+
112
+ ### `fill_diagonal`
113
+
114
+ | Exact signature | Use when | One-line description | Code and result |
115
+ |---|---|---|---|
116
+ | `fill_diagonal(a, val, wrap=False, inplace=False)` | Replace the main diagonal of an existing array with one value. | Fill the main diagonal of the given array of any dimensionality. | `q = jnp.zeros((2, 2)) * u.second; filled = u.math.fill_diagonal(q, 500 * u.ms)`<br>`# Quantity([[0.5 0. ] [0. 0.5]], "s")` |
117
+
118
+ ## Locate triangular entries
119
+
120
+ ### Lower and upper triangle indices
121
+
122
+ | API | Description & result |
123
+ |---|---|
124
+ | `tril_indices(n, k=0, m=None)` | Return row and column indices for the lower triangle of an `(n, m)` array as two plain integer arrays. |
125
+ | `triu_indices(n, k=0, m=None)` | Return row and column indices for the upper triangle of an `(n, m)` array as two plain integer arrays. |
126
+ | `tril_indices_from(arr, k=0)` | Derive lower-triangle row and column indices from a 2-D array's shape. Returns two plain integer arrays; an input `Quantity` does not give the indices a unit. |
127
+ | `triu_indices_from(arr, k=0)` | Derive upper-triangle row and column indices from a 2-D array's shape. Returns two plain integer arrays; an input `Quantity` does not give the indices a unit. |
128
+
129
+ ## Mirror pytrees
130
+
131
+ ### One or zero in every leaf
132
+
133
+ | API | Description & result |
134
+ |---|---|
135
+ | `tree_ones_like(tree)` | Replace every pytree leaf with ones while preserving structure, leaf shape, dtype, and unit; plain leaves remain plain and quantity leaves remain quantities. |
136
+ | `tree_zeros_like(tree)` | Replace every pytree leaf with zeros while preserving structure, leaf shape, dtype, and unit; plain leaves remain plain and quantity leaves remain quantities. |
137
+
138
+ ## Convert NumPy input
139
+
140
+ | API | Description & result |
141
+ |---|---|
142
+ | `from_numpy(x, unit=Unit('1'))` | Convert a NumPy array to the JAX backend. Returns a plain JAX array by default or a `Quantity` with the supplied non-trivial unit. |
143
+
144
+ ## Routing
145
+
146
+ `array_split()` appears on the tutorial page, but it is a structural operation; route it to `array-mechanics.md`.
147
+
148
+ Backend extraction and `as_numpy()` belong in `array-mechanics.md` because they cross an existing array boundary rather than create a scientific quantity from source values.
149
+
150
+ ## Cross-family gotchas
151
+
152
+ - For constructors with `unit=Unit('1')`, the unitless default produces a plain JAX array unless a quantity input supplies a unit; pass a non-trivial `Unit` to request a `Quantity`.
153
+ - The `dtype` and `shape` arguments on `*_like` functions override the prototype; otherwise its dtype and shape are retained.
154
+
155
+ ## Sources mirrored
156
+
157
+ - https://brainx.chaobrain.com/brainunit/unit_operations/array_creation.html
158
+ - https://brainx.chaobrain.com/brainunit/apis/brainunit.math.html