brainx-skill 1.0.15 → 1.0.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -1
- package/installation/lib/literature-mcp.js +7 -1
- package/manifest.json +1 -1
- package/mcp-servers/codex/README.md +46 -20
- package/mcp-servers/codex/UPSTREAM.md +20 -16
- package/mcp-servers/codex/app-server.mjs +177 -0
- package/mcp-servers/codex/cli-invocation.cjs +50 -0
- package/mcp-servers/codex/server.mjs +136 -69
- package/mcp-servers/codex/skills.json +1 -1
- package/mcp-servers/codex/test/fixtures/fake-codex.mjs +80 -3
- package/mcp-servers/codex/test/fixtures/run-server.mjs +7 -0
- package/mcp-servers/codex/test/server.test.mjs +188 -84
- package/package.json +1 -1
- package/skills/bio-neuro-lit/SKILL.md +4 -2
- package/skills/bio-neuro-lit/references/required-supplements.md +27 -0
- package/skills/brainx-acceleration/SKILL.md +30 -437
- package/skills/brainx-acceleration/references/audit-and-rewrite-patterns.md +326 -0
- package/skills/brainx-general-guard/SKILL.md +24 -8
- package/skills/brainx-install/SKILL.md +3 -3
- package/skills/brainx-install/references/compatibility-and-release-matching.md +28 -20
- package/skills/brainx-install/references/uninstall-and-cleanup.md +11 -4
- package/skills/brainx-modeling-loop/SKILL.md +117 -36
- package/skills/brainx-modeling-loop/agents/openai.yaml +2 -2
- package/skills/brainx-modeling-loop/references/mechanism-comparison.md +62 -0
- package/skills/brainx-modeling-loop/references/multiscale-coupling.md +16 -0
- package/skills/brainx-modeling-loop/references/paper-reproduction.md +42 -0
- package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +14 -14
- package/skills/brainx-modeling-loop/references/run-experiment.md +1 -1
- package/skills/brainx-modeling-loop/references/training-workflow.md +10 -8
- package/skills/brainx-visualization/SKILL.md +6 -2
- package/skills/brainx-visualization/references/neural-data-visualization.md +1 -1
- package/skills/brainx-visualization/references/statistical-and-model-visualization.md +1 -1
- package/skills/package-skills/braincell/SKILL.md +23 -14
- package/skills/package-skills/braincell/references/braintools/input-current.md +1 -1
- package/skills/package-skills/braincell/references/braintools/metric.md +72 -46
- package/skills/package-skills/braincell/references/mixions-for-adaptation.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/cv-policy-reference.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/filter-function-library.md +3 -3
- package/skills/package-skills/braincell/references/multicompartment/morphology-io-loading-validation.md +1 -1
- package/skills/package-skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +31 -43
- package/skills/package-skills/braincell/references/multicompartment/network-workflow.md +49 -0
- package/skills/package-skills/braincell/references/multicompartment/probe-reference.md +26 -114
- package/skills/package-skills/braincell/references/multicompartment/topology-building-and-visualization.md +40 -28
- package/skills/package-skills/braincell/references/scripts/cell_multicompartment_reference.py +13 -17
- package/skills/package-skills/brainevent/SKILL.md +0 -3
- package/skills/package-skills/brainevent/references/synaptic-plasticity.md +1 -1
- package/skills/package-skills/brainmass/SKILL.md +5 -3
- package/skills/package-skills/brainmass/references/brainstate/parameter-constraints-regularization.md +9 -7
- package/skills/package-skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
- package/skills/package-skills/brainmass/references/braintools/data-preprocessing.md +15 -7
- package/skills/package-skills/brainmass/references/braintools/metric.md +72 -46
- package/skills/package-skills/brainmass/references/coupling-network-api.md +3 -1
- package/skills/package-skills/brainmass/references/fitting-with-objectives-api.md +6 -6
- package/skills/package-skills/brainmass/references/horn-task-training.md +9 -9
- package/skills/package-skills/brainmass/references/modellibrary.md +12 -10
- package/skills/package-skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +5 -3
- package/skills/package-skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +10 -6
- package/skills/package-skills/brainmass/references/simulator-input-monitor-api.md +3 -1
- package/skills/package-skills/brainmass/references/visualization-analysis-api.md +17 -9
- package/skills/package-skills/brainspike/SKILL.md +201 -0
- package/skills/package-skills/brainspike/references/braintools/connectivity.md +40 -0
- package/skills/package-skills/brainspike/references/braintools/data-preprocessing.md +39 -0
- package/skills/package-skills/brainspike/references/braintools/input-current.md +55 -0
- package/skills/package-skills/brainspike/references/braintools/metric.md +36 -0
- package/skills/package-skills/brainspike/references/braintools/optimizer.md +50 -0
- package/skills/package-skills/brainspike/references/braintools/parameter-initializer.md +43 -0
- package/skills/package-skills/brainspike/references/braintools/surrogate.md +40 -0
- package/skills/package-skills/brainspike/references/migration-boundary.md +38 -0
- package/skills/package-skills/brainspike/references/model-and-readout-selection.md +41 -0
- package/skills/package-skills/brainspike/references/multirate-coupling.md +31 -0
- package/skills/package-skills/brainspike/references/multiscale-composition.md +28 -0
- package/skills/package-skills/brainspike/references/native-composition.md +52 -0
- package/skills/package-skills/brainspike/references/native-delays.md +34 -0
- package/skills/package-skills/brainspike/references/native-projections.md +43 -0
- package/skills/package-skills/brainspike/references/native-training.md +36 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/devices.md +33 -33
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/divergence-and-parity.md +15 -15
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/integration-categories.md +1 -1
- package/skills/package-skills/brainspike/references/nest-compatible/model-library.md +200 -0
- package/skills/package-skills/brainspike/references/nest-compatible/network-building.md +276 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brette_et_al_2007.py +23 -26
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_alpha.py +18 -21
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_delta.py +16 -19
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +11 -12
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +10 -11
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/spatial_gaussex.py +18 -18
- package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/synapsecollection.py +26 -29
- package/skills/package-skills/brainspike/references/nest-compatible/synapse-and-connectivity.md +166 -0
- package/skills/package-skills/brainspike/references/nest-delay-boundaries.md +31 -0
- package/skills/package-skills/brainspike/references/nonlinear-state-sharing.md +26 -0
- package/skills/package-skills/{brainpy-state → brainspike}/references/perturbation-experiment-validity.md +2 -2
- package/skills/package-skills/brainspike/references/simulator-training.md +61 -0
- package/skills/package-skills/brainspike/references/temporal-task-training.md +36 -0
- package/skills/package-skills/brainspike/scripts/advanced_native_patterns.py +76 -0
- package/skills/package-skills/brainspike/scripts/delay_workflow.py +44 -0
- package/skills/package-skills/brainspike/scripts/delayed_cue_training.py +78 -0
- package/skills/package-skills/brainspike/scripts/lif_smoke.py +31 -0
- package/skills/package-skills/brainspike/scripts/multiscale_workflow.py +35 -0
- package/skills/package-skills/brainspike/scripts/native_ei_network.py +47 -0
- package/skills/package-skills/brainspike/scripts/native_workflows.py +77 -0
- package/skills/package-skills/brainspike/scripts/nest_boundary_workflows.py +108 -0
- package/skills/package-skills/brainspike/scripts/train_native_snn.py +65 -0
- package/skills/package-skills/brainspike/scripts/train_nest_simulator.py +69 -0
- package/skills/package-skills/brainspike/scripts/train_nest_simulator_two_weights.py +220 -0
- package/skills/package-skills/brainstate/SKILL.md +16 -21
- package/skills/package-skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +1 -138
- package/skills/package-skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
- package/skills/package-skills/brainstate/references/brainstate/delay-buffers.md +45 -0
- package/skills/package-skills/brainstate/references/brainstate/parameter-constraints-regularization.md +9 -7
- package/skills/package-skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
- package/skills/package-skills/brainstate/references/brainstate/randomness-and-reproducibility.md +6 -4
- package/skills/package-skills/brainstate/references/brainstate/transformation-grad-expansion.md +4 -4
- package/skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md +1 -1
- package/skills/package-skills/brainstate/references/braintools-optimizer-reference.md +16 -0
- package/skills/package-skills/brainstate/references/libraries/prebuilt-layer-library.md +1 -1
- package/skills/package-skills/brainstate/references/simulation-environment.md +5 -5
- package/skills/package-skills/braintrace/SKILL.md +17 -38
- package/skills/package-skills/braintrace/references/Drtrl.md +9 -26
- package/skills/package-skills/braintrace/references/algorithm selection.md +7 -12
- package/skills/package-skills/braintrace/references/batching.md +15 -35
- package/skills/package-skills/braintrace/references/compiler_internal.md +1 -1
- package/skills/package-skills/braintrace/references/custom algorithms.md +1 -2
- package/skills/package-skills/braintrace/references/customizing_primitive_transforms.md +26 -15
- package/skills/package-skills/braintrace/references/pp_pprop workflow.md +5 -139
- package/skills/package-skills/brainunit/SKILL.md +7 -2
- package/skills/package-skills/brainunit/references/array-mechanics/functional-structural-api.md +1 -1
- package/skills/package-skills/brainunit/references/math-function-library.md +2 -2
- package/skills/package-skills/brainunit/references/typing-and-runtime-validation.md +5 -2
- package/skills/package-skills/brainevent/references/scripts/102_EI_net_1996.py +0 -107
- package/skills/package-skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +0 -168
- package/skills/package-skills/brainevent/references/scripts/coba_ei_teaching.py +0 -356
- package/skills/package-skills/brainpy-state/SKILL.md +0 -247
- package/skills/package-skills/brainpy-state/references/array-creation.md +0 -158
- package/skills/package-skills/brainpy-state/references/brain-dynamics-delay-protocol.md +0 -147
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/analysis.md +0 -150
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +0 -373
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -150
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +0 -175
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +0 -286
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +0 -111
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -163
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -113
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -136
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -222
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -123
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +0 -107
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -185
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/integrators.md +0 -181
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +0 -102
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +0 -147
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +0 -159
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +0 -127
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +0 -167
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +0 -107
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -186
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +0 -104
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +0 -89
- package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +0 -253
- package/skills/package-skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +0 -334
- package/skills/package-skills/brainpy-state/references/braintools/connectivity.md +0 -206
- package/skills/package-skills/brainpy-state/references/braintools/data-preprocessing.md +0 -79
- package/skills/package-skills/brainpy-state/references/braintools/input-current.md +0 -199
- package/skills/package-skills/brainpy-state/references/braintools/metric.md +0 -152
- package/skills/package-skills/brainpy-state/references/braintools/optimizer.md +0 -179
- package/skills/package-skills/brainpy-state/references/braintools/parameter-initializer.md +0 -183
- package/skills/package-skills/brainpy-state/references/braintools/surrogate.md +0 -147
- package/skills/package-skills/brainpy-state/references/component-selection.md +0 -288
- package/skills/package-skills/brainpy-state/references/nest-compatible/model-library.md +0 -200
- package/skills/package-skills/brainpy-state/references/nest-compatible/nest-workflow.md +0 -156
- package/skills/package-skills/brainpy-state/references/nest-compatible/network-building.md +0 -264
- package/skills/package-skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +0 -153
- package/skills/package-skills/brainpy-state/references/projection-patterns.md +0 -127
- package/skills/package-skills/brainpy-state/references/scripts/103_COBA_2005.py +0 -86
- package/skills/package-skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +0 -181
- package/skills/package-skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +0 -156
- package/skills/package-skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +0 -111
- package/skills/package-skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -221
- package/skills/package-skills/brainpy-state/references/scripts/sound_localization.py +0 -240
- package/skills/package-skills/brainpy-state/references/scripts/training-snn.py +0 -119
|
@@ -1,356 +0,0 @@
|
|
|
1
|
-
"""COBA E/I balanced network -- a minimal teaching model on BrainEvent CSR.
|
|
2
|
-
|
|
3
|
-
The network is the classic Vogels & Abbott (2005) conductance-based (COBA)
|
|
4
|
-
excitatory/inhibitory random network:
|
|
5
|
-
|
|
6
|
-
* ``N`` leaky integrate-and-fire neurons with an absolute refractory period,
|
|
7
|
-
split 80% excitatory / 20% inhibitory.
|
|
8
|
-
* Every neuron projects to ``CONN_NUM`` randomly chosen postsynaptic targets
|
|
9
|
-
(fixed out-degree), stored as one connection matrix per population. The
|
|
10
|
-
storage format is selectable -- ``fcn``, ``csr`` or ``dense``, see
|
|
11
|
-
``make_connection`` -- and does not change the dynamics.
|
|
12
|
-
* Each spike deposits conductance into an exponentially decaying synapse
|
|
13
|
-
(``Expon``); the conductance drives the membrane through a reversal
|
|
14
|
-
potential (``COBA``).
|
|
15
|
-
|
|
16
|
-
The whole simulation is a single loop over time:
|
|
17
|
-
|
|
18
|
-
spikes -> CSR mat-vec -> synaptic conductance -> membrane -> spikes
|
|
19
|
-
|
|
20
|
-
Everything is spelled out inline: one connection builder, one network class,
|
|
21
|
-
one simulation function.
|
|
22
|
-
|
|
23
|
-
Run with the BrainEvent environment::
|
|
24
|
-
|
|
25
|
-
python coba_ei_teaching.py --conn csr
|
|
26
|
-
"""
|
|
27
|
-
|
|
28
|
-
from __future__ import annotations
|
|
29
|
-
|
|
30
|
-
import argparse
|
|
31
|
-
|
|
32
|
-
import brainevent
|
|
33
|
-
import brainpy
|
|
34
|
-
import brainstate
|
|
35
|
-
import braintools
|
|
36
|
-
import brainunit as u
|
|
37
|
-
import jax
|
|
38
|
-
import matplotlib.pyplot as plt
|
|
39
|
-
import numpy as np
|
|
40
|
-
|
|
41
|
-
# --------------------------------------------------------------------------
|
|
42
|
-
# Parameters (mirrors config.txt)
|
|
43
|
-
# --------------------------------------------------------------------------
|
|
44
|
-
|
|
45
|
-
PRECISION = 32 # float32 everywhere
|
|
46
|
-
DT = 0.1 * u.ms # integration step
|
|
47
|
-
DURATION = 100. * u.ms # simulated time
|
|
48
|
-
|
|
49
|
-
SCALE = 1 # network size multiplier
|
|
50
|
-
N_BASE = 4000 # neurons per unit of scale
|
|
51
|
-
EXC_FRACTION = 0.8 # 80% excitatory / 20% inhibitory
|
|
52
|
-
|
|
53
|
-
# regime.
|
|
54
|
-
CONN_NUM = 80 # out-degree: targets per presynaptic neuron
|
|
55
|
-
CONN_NUM_BASE = 80 # reference out-degree the weights were tuned for
|
|
56
|
-
|
|
57
|
-
# Synaptic weights. The reference COBA model is dimensionless:
|
|
58
|
-
# dV/dt = (V_rest - V + I_offset + g*(E - V)) / tau_m
|
|
59
|
-
# with V in "mV numbers" and g a conductance relative to the leak. BrainPy's
|
|
60
|
-
# LIFRef is dimensionful -- dV/dt = (V_rest - V + R*I) / tau_m with R = 1 ohm --
|
|
61
|
-
# so the term R*g*(E - V) reproduces the reference only when g is expressed in
|
|
62
|
-
# *siemens*: 1 ohm * 1 S * 1 mV = 1 mV. Writing these as mS would make the
|
|
63
|
-
# synapses 1000x too weak and leave the network driven purely by I_OFFSET.
|
|
64
|
-
EXC_WEIGHT_BASE = 0.6 * u.siemens
|
|
65
|
-
INH_WEIGHT_BASE = 6.7 * u.siemens
|
|
66
|
-
|
|
67
|
-
# LIF neuron
|
|
68
|
-
V_REST = -60. * u.mV
|
|
69
|
-
V_RESET = -60. * u.mV
|
|
70
|
-
V_TH = -50. * u.mV
|
|
71
|
-
TAU_M = 20. * u.ms
|
|
72
|
-
TAU_REF = 5. * u.ms
|
|
73
|
-
V_INIT_MEAN = -55. * u.mV
|
|
74
|
-
V_INIT_STD = 5. * u.mV
|
|
75
|
-
|
|
76
|
-
# COBA synapses
|
|
77
|
-
E_EXC = 0. * u.mV
|
|
78
|
-
E_INH = -80. * u.mV
|
|
79
|
-
TAU_SYN_EXC = 5. * u.ms
|
|
80
|
-
TAU_SYN_INH = 10. * u.ms
|
|
81
|
-
|
|
82
|
-
# Constant drive. Same convention as the weights: R * 20 mA = 1 ohm * 20 mA
|
|
83
|
-
# = 20 mV, matching the reference model's dimensionless i_offset = 20.
|
|
84
|
-
I_OFFSET = 20. * u.mA
|
|
85
|
-
|
|
86
|
-
CONN_SEED = 123
|
|
87
|
-
STATE_SEED = 456
|
|
88
|
-
|
|
89
|
-
# Neurons whose analogue variables (V, conductances) get recorded -- think of
|
|
90
|
-
# it as a 64-electrode array. Most neurons in this network are silent over a
|
|
91
|
-
# 100 ms window, so recording a group and plotting the most active one is more
|
|
92
|
-
# informative than picking a fixed index.
|
|
93
|
-
PROBE_NEURONS = np.arange(64)
|
|
94
|
-
|
|
95
|
-
brainstate.environ.set(dt=DT, precision=PRECISION)
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
# --------------------------------------------------------------------------
|
|
99
|
-
# Connectivity
|
|
100
|
-
#
|
|
101
|
-
# The same connection pattern can be stored three different ways. All of them
|
|
102
|
-
# answer `spikes @ conn` with the same postsynaptic input; they differ only in
|
|
103
|
-
# what is kept in memory and which kernel runs:
|
|
104
|
-
#
|
|
105
|
-
# 'fcn' brainevent.FixedNumPerPre -- an (n_pre, out_degree) index matrix.
|
|
106
|
-
# Exploits the fact that every row has the same length, so no row
|
|
107
|
-
# pointer is needed. This is what the reference benchmark uses.
|
|
108
|
-
# 'csr' brainevent.CSR -- flat indices plus a row pointer. The general
|
|
109
|
-
# sparse format; it also allows rows of unequal length.
|
|
110
|
-
# 'dense' a plain (n_pre, n_post) array. Easiest to read, but O(N^2) memory
|
|
111
|
-
# and the kernel touches every entry, spike or not.
|
|
112
|
-
#
|
|
113
|
-
# All three share `sample_targets`, so they produce bit-identical spike trains.
|
|
114
|
-
#
|
|
115
|
-
# Weights are homogeneous (one shared scalar), so for 'fcn' and 'csr' the
|
|
116
|
-
# connectivity costs only the indices.
|
|
117
|
-
# --------------------------------------------------------------------------
|
|
118
|
-
|
|
119
|
-
CONN_KIND = 'fcn' # 'fcn' | 'csr' | 'dense'
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
def sample_targets(n_pre: int, n_post: int, out_degree: int, seed: int) -> np.ndarray:
|
|
123
|
-
"""Row ``i`` lists the ``out_degree`` postsynaptic targets of neuron ``i``."""
|
|
124
|
-
rng = np.random.default_rng(seed)
|
|
125
|
-
return rng.integers(0, n_post, size=(n_pre, out_degree), dtype=np.int32)
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
def make_connection(n_pre: int, n_post: int, out_degree: int, weight, seed: int, kind=CONN_KIND):
|
|
129
|
-
"""Build a ``(n_pre, n_post)`` connection matrix in the requested format."""
|
|
130
|
-
w = u.math.asarray(weight, dtype=brainstate.environ.dftype())
|
|
131
|
-
shape = (n_pre, n_post)
|
|
132
|
-
|
|
133
|
-
if kind == 'fcn':
|
|
134
|
-
targets = sample_targets(n_pre, n_post, out_degree, seed)
|
|
135
|
-
return brainevent.FixedNumPerPre(w, targets, shape=shape)
|
|
136
|
-
|
|
137
|
-
if kind == 'csr':
|
|
138
|
-
# Every row has the same length, so the row pointer is just a ramp.
|
|
139
|
-
indices = sample_targets(n_pre, n_post, out_degree, seed).reshape(-1)
|
|
140
|
-
indptr = np.arange(n_pre + 1, dtype=np.int32) * np.int32(out_degree)
|
|
141
|
-
return brainevent.CSR((w, indices, indptr), shape=shape)
|
|
142
|
-
|
|
143
|
-
if kind == 'dense':
|
|
144
|
-
# `add.at` accumulates, so a target drawn twice gets twice the weight --
|
|
145
|
-
# the same thing the sparse formats do with duplicate column indices.
|
|
146
|
-
targets = sample_targets(n_pre, n_post, out_degree, seed)
|
|
147
|
-
mask = np.zeros(shape, dtype=brainstate.environ.dftype())
|
|
148
|
-
np.add.at(mask, (np.repeat(np.arange(n_pre), out_degree), targets.reshape(-1)), 1.)
|
|
149
|
-
return u.math.asarray(mask) * w
|
|
150
|
-
|
|
151
|
-
raise ValueError(f"kind must be 'fcn', 'csr', 'dense', got {kind!r}.")
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
# --------------------------------------------------------------------------
|
|
155
|
-
# The network
|
|
156
|
-
# --------------------------------------------------------------------------
|
|
157
|
-
|
|
158
|
-
class EINet(brainstate.nn.Module):
|
|
159
|
-
"""Excitatory/inhibitory COBA network.
|
|
160
|
-
|
|
161
|
-
Layout: neurons ``[0, n_exc)`` are excitatory, ``[n_exc, num)`` inhibitory.
|
|
162
|
-
Both populations project onto *all* ``num`` neurons, so the two CSR matrices
|
|
163
|
-
have shapes ``(n_exc, num)`` and ``(n_inh, num)``.
|
|
164
|
-
"""
|
|
165
|
-
|
|
166
|
-
def __init__(self, scale: float = SCALE, conn_num: int = CONN_NUM, conn_kind: str = CONN_KIND):
|
|
167
|
-
super().__init__()
|
|
168
|
-
|
|
169
|
-
self.num = int(N_BASE * scale)
|
|
170
|
-
self.n_exc = int(EXC_FRACTION * self.num)
|
|
171
|
-
self.n_inh = self.num - self.n_exc
|
|
172
|
-
self.conn_kind = conn_kind
|
|
173
|
-
|
|
174
|
-
# Weights were tuned at CONN_NUM_BASE synapses per neuron; keep the total
|
|
175
|
-
# synaptic drive constant when the out-degree changes.
|
|
176
|
-
exc_weight = EXC_WEIGHT_BASE * CONN_NUM_BASE / conn_num
|
|
177
|
-
inh_weight = INH_WEIGHT_BASE * CONN_NUM_BASE / conn_num
|
|
178
|
-
|
|
179
|
-
self.exc_conn = make_connection(self.n_exc, self.num, conn_num, exc_weight,
|
|
180
|
-
CONN_SEED, kind=conn_kind)
|
|
181
|
-
self.inh_conn = make_connection(self.n_inh, self.num, conn_num, inh_weight,
|
|
182
|
-
CONN_SEED + 1, kind=conn_kind)
|
|
183
|
-
|
|
184
|
-
# Neurons.
|
|
185
|
-
brainstate.random.seed(STATE_SEED)
|
|
186
|
-
self.N = brainpy.state.LIFRef(
|
|
187
|
-
self.num,
|
|
188
|
-
V_rest=V_REST,
|
|
189
|
-
V_th=V_TH,
|
|
190
|
-
V_reset=V_RESET,
|
|
191
|
-
tau=TAU_M,
|
|
192
|
-
tau_ref=TAU_REF,
|
|
193
|
-
V_initializer=braintools.init.Normal(V_INIT_MEAN, V_INIT_STD),
|
|
194
|
-
)
|
|
195
|
-
|
|
196
|
-
# Exponentially decaying conductances, one channel per population.
|
|
197
|
-
self.exc_syn = brainpy.state.Expon(self.num, tau=TAU_SYN_EXC)
|
|
198
|
-
self.inh_syn = brainpy.state.Expon(self.num, tau=TAU_SYN_INH)
|
|
199
|
-
|
|
200
|
-
# Conductance -> current, through the reversal potentials.
|
|
201
|
-
self.exc_out = brainpy.state.COBA(E=E_EXC)
|
|
202
|
-
self.inh_out = brainpy.state.COBA(E=E_INH)
|
|
203
|
-
self.N.add_current_input('exc_coba', self.exc_out)
|
|
204
|
-
self.N.add_current_input('inh_coba', self.inh_out)
|
|
205
|
-
|
|
206
|
-
def update(self, t, inp):
|
|
207
|
-
with brainstate.environ.context(t=t):
|
|
208
|
-
spk = self.N.get_spike() != 0.
|
|
209
|
-
|
|
210
|
-
# The event-driven mat-vec. Wrapping the spike vector in a
|
|
211
|
-
# `BinaryArray` is what tells brainevent to dispatch an event
|
|
212
|
-
# kernel: only the rows of neurons that spiked this step are read,
|
|
213
|
-
# and their weights are scattered onto the postsynaptic targets.
|
|
214
|
-
# This line is identical for every CONN_KIND -- the format of
|
|
215
|
-
# `exc_conn` picks the kernel.
|
|
216
|
-
exc_input = brainevent.BinaryArray(spk[:self.n_exc]) @ self.exc_conn
|
|
217
|
-
inh_input = brainevent.BinaryArray(spk[self.n_exc:]) @ self.inh_conn
|
|
218
|
-
|
|
219
|
-
self.exc_out.bind_cond(self.exc_syn(exc_input))
|
|
220
|
-
self.inh_out.bind_cond(self.inh_syn(inh_input))
|
|
221
|
-
|
|
222
|
-
return self.N(inp)
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
# --------------------------------------------------------------------------
|
|
226
|
-
# Simulation
|
|
227
|
-
# --------------------------------------------------------------------------
|
|
228
|
-
|
|
229
|
-
def simulate(net: EINet, duration=DURATION, probe=PROBE_NEURONS):
|
|
230
|
-
"""Run the network for ``duration``; return spikes plus the probe traces.
|
|
231
|
-
|
|
232
|
-
The whole time loop is compiled as one XLA program: ``for_loop`` scans over
|
|
233
|
-
the time points, carrying the neuron/synapse states, and stacks whatever the
|
|
234
|
-
step function returns.
|
|
235
|
-
|
|
236
|
-
Spikes are recorded for the whole population (that is what the raster and
|
|
237
|
-
the firing rate need). The analogue variables -- membrane potential and the
|
|
238
|
-
two synaptic conductances -- are recorded only for the neurons in ``probe``,
|
|
239
|
-
like sticking electrodes into a handful of cells: recording all of them
|
|
240
|
-
would cost ``n_steps x num`` floats per variable.
|
|
241
|
-
|
|
242
|
-
States are created *before* the JIT boundary so that ``net.N.V`` and the
|
|
243
|
-
synaptic conductances still hold real values after the run.
|
|
244
|
-
"""
|
|
245
|
-
brainstate.nn.init_all_states(net)
|
|
246
|
-
times = u.math.arange(0. * u.ms, duration, DT)
|
|
247
|
-
|
|
248
|
-
@brainstate.transform.jit
|
|
249
|
-
def run():
|
|
250
|
-
def step(t):
|
|
251
|
-
spikes = net.update(t, I_OFFSET)
|
|
252
|
-
return (spikes,
|
|
253
|
-
net.N.V.value[probe],
|
|
254
|
-
net.exc_syn.g.value[probe],
|
|
255
|
-
net.inh_syn.g.value[probe])
|
|
256
|
-
|
|
257
|
-
return brainstate.transform.for_loop(step, times)
|
|
258
|
-
|
|
259
|
-
spikes, V, g_exc, g_inh = run()
|
|
260
|
-
return times, spikes, V, g_exc, g_inh
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
# --------------------------------------------------------------------------
|
|
264
|
-
# Figures
|
|
265
|
-
# --------------------------------------------------------------------------
|
|
266
|
-
|
|
267
|
-
def plot_summary(net, times, spikes, V, g_exc, g_inh, path='coba_ei_summary.png'):
|
|
268
|
-
"""Four views of the same run."""
|
|
269
|
-
t = np.asarray(times.to_decimal(u.ms))
|
|
270
|
-
spikes = np.asarray(spikes) != 0.
|
|
271
|
-
dt_s = DT.to_decimal(u.second)
|
|
272
|
-
|
|
273
|
-
# Panels 3 and 4 follow one cell: the most active of the recorded neurons.
|
|
274
|
-
col = int(spikes[:, PROBE_NEURONS].sum(0).argmax())
|
|
275
|
-
cell = int(PROBE_NEURONS[col])
|
|
276
|
-
V, g_exc, g_inh = V[:, col], g_exc[:, col], g_inh[:, col]
|
|
277
|
-
cell_rate = spikes[:, cell].sum() / DURATION.to_decimal(u.second)
|
|
278
|
-
|
|
279
|
-
# The two synaptic currents, as they enter dV/dt: R * g * (E - V).
|
|
280
|
-
i_exc = (net.N.R * g_exc * (E_EXC - V)).to_decimal(u.mV)
|
|
281
|
-
i_inh = (net.N.R * g_inh * (E_INH - V)).to_decimal(u.mV)
|
|
282
|
-
i_ext = (net.N.R * I_OFFSET).to_decimal(u.mV)
|
|
283
|
-
|
|
284
|
-
fig, ax = plt.subplots(4, 1, figsize=(10, 11), sharex=True)
|
|
285
|
-
|
|
286
|
-
# 1. Raster: who spiked when.
|
|
287
|
-
step, neuron = np.nonzero(spikes)
|
|
288
|
-
ax[0].scatter(t[step], neuron, s=0.4, c='k', marker='.')
|
|
289
|
-
ax[0].axhline(net.n_exc, color='tab:red', lw=0.8)
|
|
290
|
-
ax[0].set_ylabel('neuron index')
|
|
291
|
-
ax[0].set_title(f'raster ({net.num} neurons, red line = exc/inh boundary)')
|
|
292
|
-
|
|
293
|
-
# 2. Population rate: the network view of the same spikes.
|
|
294
|
-
bin_steps = max(1, int(round(1. * u.ms / DT))) # 1 ms bins
|
|
295
|
-
n_bins = spikes.shape[0] // bin_steps
|
|
296
|
-
pop = spikes[:n_bins * bin_steps].reshape(n_bins, bin_steps, -1).sum((1, 2))
|
|
297
|
-
ax[1].plot(t[:n_bins * bin_steps:bin_steps], pop / net.num / (bin_steps * dt_s), 'k-', lw=.9)
|
|
298
|
-
ax[1].set_ylabel('population rate (Hz)')
|
|
299
|
-
ax[1].set_title('population rate')
|
|
300
|
-
|
|
301
|
-
# 3. Membrane potential of that one neuron.
|
|
302
|
-
v_mv = V.to_decimal(u.mV)
|
|
303
|
-
ax[2].plot(t, v_mv, 'k-', lw=.8)
|
|
304
|
-
ax[2].plot(t[spikes[:, cell]], v_mv[spikes[:, cell]], '|', color='tab:orange',
|
|
305
|
-
ms=10, mew=1.2, label='spike')
|
|
306
|
-
ax[2].axhline(V_TH.to_decimal(u.mV), color='tab:red', ls='--', lw=.8, label='V_th')
|
|
307
|
-
ax[2].axhline(V_REST.to_decimal(u.mV), color='tab:blue', ls=':', lw=.8, label='V_rest')
|
|
308
|
-
ax[2].set_ylabel('V (mV)')
|
|
309
|
-
ax[2].set_title(f'membrane potential of neuron {cell}')
|
|
310
|
-
ax[2].legend(loc='upper right', fontsize=8)
|
|
311
|
-
|
|
312
|
-
# 4. The synaptic currents driving that neuron. The point of the balanced
|
|
313
|
-
# state: excitation and inhibition are each far larger than the external
|
|
314
|
-
# drive, and nearly cancel. What is left fluctuates around threshold.
|
|
315
|
-
ax[3].plot(t, i_exc, color='tab:red', lw=.7, label='R*g_exc*(E_exc - V)')
|
|
316
|
-
ax[3].plot(t, i_inh, color='tab:blue', lw=.7, label='R*g_inh*(E_inh - V)')
|
|
317
|
-
ax[3].plot(t, i_exc + i_inh + i_ext, color='k', lw=.9, label='total (incl. I_offset)')
|
|
318
|
-
ax[3].axhline(0., color='0.6', lw=.5)
|
|
319
|
-
ax[3].set_ylabel('contribution to dV/dt (mV)')
|
|
320
|
-
ax[3].set_xlabel('time (ms)')
|
|
321
|
-
ax[3].set_title('synaptic input to that neuron')
|
|
322
|
-
ax[3].legend(loc='upper right', fontsize=8)
|
|
323
|
-
|
|
324
|
-
fig.tight_layout()
|
|
325
|
-
fig.savefig(path, dpi=150)
|
|
326
|
-
return path
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
def main(conn_kind: str = CONN_KIND):
|
|
330
|
-
|
|
331
|
-
net = EINet(conn_kind=conn_kind)
|
|
332
|
-
|
|
333
|
-
times, spikes, V, g_exc, g_inh = simulate(net)
|
|
334
|
-
|
|
335
|
-
spk = np.asarray(spikes) != 0.
|
|
336
|
-
rate = spk.sum() / net.num / DURATION.to_decimal(u.second)
|
|
337
|
-
print(f'{net.num} neurons ({net.n_exc} exc / {net.n_inh} inh), '
|
|
338
|
-
f'{CONN_NUM} synapses per neuron, conn_kind={conn_kind!r} '
|
|
339
|
-
f'({type(net.exc_conn).__name__})')
|
|
340
|
-
print(f'mean firing rate over {DURATION}: {rate:.2f} Hz')
|
|
341
|
-
|
|
342
|
-
# Irregularity: the coefficient of variation of the inter-spike intervals,
|
|
343
|
-
# pooled over neurons. ~1 means Poisson-like, ~0 means clock-like.
|
|
344
|
-
dt_ms = DT.to_decimal(u.ms)
|
|
345
|
-
isis = np.concatenate([np.diff(np.flatnonzero(spk[:, i])) * dt_ms
|
|
346
|
-
for i in range(net.num) if spk[:, i].sum() > 1])
|
|
347
|
-
print(f'ISI CV = {isis.std() / isis.mean():.2f} (1.0 = Poisson, 0 = regular)')
|
|
348
|
-
|
|
349
|
-
print(f'summary figure saved to {plot_summary(net, times, spikes, V, g_exc, g_inh)}')
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
if __name__ == '__main__':
|
|
353
|
-
parser = argparse.ArgumentParser(description=__doc__)
|
|
354
|
-
parser.add_argument('--conn', default=CONN_KIND, choices=['fcn', 'csr', 'dense'],
|
|
355
|
-
help='connectivity storage format (default: %(default)s)')
|
|
356
|
-
main(parser.parse_args().conn)
|
|
@@ -1,247 +0,0 @@
|
|
|
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. Use as the legacy BrainPy routing entry only when an existing codebase uses legacy `brainpy`, uses neither units nor BrainTrace, and the user explicitly asks to preserve it.
|
|
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
|
-
Open `references/brainPy(legacy)/brainpy legacy workflow.md` only when the workspace already contains legacy `brainpy` code, contains no BrainUnit quantities, unit-aware APIs, and when the user explicitly asks to preserve old BrainPy. Use native BrainPy-State for new project is HIGHLY RECOMMENDED; use BrainPy-State with BrainCell for all cellular modeling.
|
|
15
|
-
|
|
16
|
-
Treat that workflow as the only first-level legacy reference. Do not open or route directly to any other Markdown under `references/brainPy(legacy)/`; let the workflow select those second-level references.
|
|
17
|
-
|
|
18
|
-
## Underlying principle of BrainPy-State
|
|
19
|
-
|
|
20
|
-
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.
|
|
21
|
-
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.
|
|
22
|
-
|
|
23
|
-
### API structure
|
|
24
|
-
|
|
25
|
-
| API family | Use |
|
|
26
|
-
|---|---|
|
|
27
|
-
| Base Classes | Find the shared dynamics, neuron, and synapse abstractions used to implement custom BrainPy-State components. |
|
|
28
|
-
| BrainPy-style Neurons | Select native point-neuron dynamics, from integrate-and-fire models to conductance-based models. |
|
|
29
|
-
| BrainPy-style Synapses | Select native synaptic dynamics, from simple temporal filters to biological receptor models. |
|
|
30
|
-
| BrainPy-style Projections | Connect populations through projection classes, projection helper functions, or gap-junction projections. |
|
|
31
|
-
| BrainPy-style Synaptic Outputs | Convert synaptic state into current- or conductance-based postsynaptic input. |
|
|
32
|
-
| BrainPy-style Plasticity | Add short-term facilitation or depression to synaptic transmission. |
|
|
33
|
-
| BrainPy-style Readouts | Decode spiking activity through native readout models. |
|
|
34
|
-
| BrainPy-style Input Generators | Generate spike trains or time-varying simulation inputs. |
|
|
35
|
-
|
|
36
|
-
### 1. Choose and run neuron dynamics
|
|
37
|
-
|
|
38
|
-
A neuron call advances one `dt`, mutates its registered dynamical State, and exposes the current spike through `get_spike()`; initialize before every independent rollout, set `V_initializer` whenever startup voltage affects the result, and lower the complete time loop through `brainstate.transform`.
|
|
39
|
-
|
|
40
|
-
| API | Description |
|
|
41
|
-
|---|---|
|
|
42
|
-
| `brainpy.state.LIFRef(..., V_initializer=...)` | 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. `V_rest` sets the resting dynamics but does not set the initial membrane State, so pass an intentional initializer when startup spikes or transients matter. |
|
|
43
|
-
| `braintools.init.Constant(value)` | Use as `V_initializer` when every neuron must start at one known voltage; initialization creates membrane State at that value. Use a documented distribution instead when initial heterogeneity is part of the model. |
|
|
44
|
-
| `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. |
|
|
45
|
-
| `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. |
|
|
46
|
-
| `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. |
|
|
47
|
-
| `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. |
|
|
48
|
-
| `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. |
|
|
49
|
-
| `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. |
|
|
50
|
-
|
|
51
|
-
```python
|
|
52
|
-
import brainpy
|
|
53
|
-
import brainstate
|
|
54
|
-
import braintools
|
|
55
|
-
import brainunit as u
|
|
56
|
-
|
|
57
|
-
with brainstate.environ.context(dt=0.1 * u.ms):
|
|
58
|
-
neuron = brainpy.state.LIFRef(
|
|
59
|
-
1,
|
|
60
|
-
R=1.0 * u.ohm,
|
|
61
|
-
tau=20.0 * u.ms,
|
|
62
|
-
V_rest=-60.0 * u.mV,
|
|
63
|
-
V_th=-50.0 * u.mV,
|
|
64
|
-
V_reset=-60.0 * u.mV,
|
|
65
|
-
tau_ref=5.0 * u.ms,
|
|
66
|
-
V_initializer=braintools.init.Constant(-60.0 * u.mV),
|
|
67
|
-
)
|
|
68
|
-
brainstate.nn.init_all_states(neuron)
|
|
69
|
-
times = u.math.arange(
|
|
70
|
-
0.0 * u.ms,
|
|
71
|
-
200.0 * u.ms,
|
|
72
|
-
brainstate.environ.get_dt(),
|
|
73
|
-
)
|
|
74
|
-
|
|
75
|
-
def step(t):
|
|
76
|
-
with brainstate.environ.context(t=t):
|
|
77
|
-
neuron(25.0 * u.mA)
|
|
78
|
-
return neuron.V.value, neuron.get_spike()
|
|
79
|
-
|
|
80
|
-
voltages, spikes = brainstate.transform.for_loop(step, times)
|
|
81
|
-
|
|
82
|
-
assert voltages.shape == (2000, 1)
|
|
83
|
-
assert spikes.shape == (2000, 1)
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
Open `references/braintools/input-current.md` when a direct current protocol needs timed sections, pulses, waveforms, stochastic processes, or composition. Generate the complete time-major protocol once under the rollout `dt` and pass it as an input to `for_loop`; do not rebuild named sections or pulses from time predicates inside the model step. 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.
|
|
87
|
-
|
|
88
|
-
### 2. Compose synapses and projections
|
|
89
|
-
|
|
90
|
-
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; when recurrent excitation, mutual inhibition, or spike-driven connectivity is a point-neuron mechanism, represent it with explicit projections instead of a hand-written population-rate feedback `State`, and route aggregate rate coupling to BrainMass.
|
|
91
|
-
|
|
92
|
-
| API | Description |
|
|
93
|
-
|---|---|
|
|
94
|
-
| `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. |
|
|
95
|
-
| `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. |
|
|
96
|
-
| `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. |
|
|
97
|
-
| `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`. |
|
|
98
|
-
| `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. |
|
|
99
|
-
| `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. |
|
|
100
|
-
|
|
101
|
-
```python
|
|
102
|
-
import brainpy
|
|
103
|
-
import brainstate
|
|
104
|
-
import braintools
|
|
105
|
-
import brainunit as u
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
class TwoPop(brainstate.nn.Module):
|
|
109
|
-
def __init__(self, n_pre=20, n_post=10):
|
|
110
|
-
super().__init__()
|
|
111
|
-
self.pre = brainpy.state.LIFRef(
|
|
112
|
-
n_pre,
|
|
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
|
-
V_initializer=braintools.init.Constant(-60.0 * u.mV),
|
|
119
|
-
)
|
|
120
|
-
self.post = brainpy.state.LIFRef(
|
|
121
|
-
n_post,
|
|
122
|
-
tau=20.0 * u.ms,
|
|
123
|
-
tau_ref=5.0 * u.ms,
|
|
124
|
-
V_rest=-60.0 * u.mV,
|
|
125
|
-
V_th=-50.0 * u.mV,
|
|
126
|
-
V_reset=-60.0 * u.mV,
|
|
127
|
-
V_initializer=braintools.init.Constant(-60.0 * u.mV),
|
|
128
|
-
)
|
|
129
|
-
self.proj = brainpy.state.AlignPostProj(
|
|
130
|
-
comm=brainstate.nn.EventFixedProb(
|
|
131
|
-
n_pre,
|
|
132
|
-
n_post,
|
|
133
|
-
conn_num=0.5,
|
|
134
|
-
conn_weight=0.5 * u.mS,
|
|
135
|
-
),
|
|
136
|
-
syn=brainpy.state.Expon.desc(n_post, tau=5.0 * u.ms),
|
|
137
|
-
out=brainpy.state.COBA.desc(E=0.0 * u.mV),
|
|
138
|
-
post=self.post,
|
|
139
|
-
)
|
|
140
|
-
|
|
141
|
-
def update(self, t, drive):
|
|
142
|
-
with brainstate.environ.context(t=t):
|
|
143
|
-
pre_spikes = self.pre.get_spike() != 0.0
|
|
144
|
-
self.proj(pre_spikes)
|
|
145
|
-
self.pre(drive)
|
|
146
|
-
self.post(0.0 * u.mA)
|
|
147
|
-
return self.post.V.value, self.proj.syn.g.value
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
with brainstate.environ.context(dt=0.1 * u.ms):
|
|
151
|
-
net = TwoPop()
|
|
152
|
-
brainstate.nn.init_all_states(net)
|
|
153
|
-
times = u.math.arange(0.0 * u.ms, 200.0 * u.ms, brainstate.environ.get_dt())
|
|
154
|
-
post_voltage, conductance = brainstate.transform.for_loop(
|
|
155
|
-
lambda t: net.update(t, 30.0 * u.mA),
|
|
156
|
-
times,
|
|
157
|
-
)
|
|
158
|
-
|
|
159
|
-
assert post_voltage.shape == (2000, 10)
|
|
160
|
-
assert conductance.shape == (2000, 10)
|
|
161
|
-
```
|
|
162
|
-
|
|
163
|
-
Open `references/braintools/connectivity.md` first when geometry, distance, degree, modules, or another named topology determines which neuron pairs connect; generate the topology before choosing its BrainEvent representation. Open `references/projection-patterns.md` before implementing recurrent excitation, mutual inhibition, or other spike-driven connectivity; it owns AlignPre versus AlignPost, communication, delays, direct/delta input, short-term plasticity, and electrical coupling. Open `skills/package-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.
|
|
164
|
-
|
|
165
|
-
### 3. Train a spiking network
|
|
166
|
-
|
|
167
|
-
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.
|
|
168
|
-
|
|
169
|
-
| API | Description |
|
|
170
|
-
|---|---|
|
|
171
|
-
| `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. |
|
|
172
|
-
| `model.states(brainstate.ParamState)` | Use to select trainable parameters; it excludes membrane voltage, conductance, spike history, and other rollout State. |
|
|
173
|
-
| `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. |
|
|
174
|
-
| `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)`. |
|
|
175
|
-
| `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. |
|
|
176
|
-
|
|
177
|
-
```python
|
|
178
|
-
# Given a stateful net whose update() returns per-step logits [batch, classes].
|
|
179
|
-
params = net.states(brainstate.ParamState)
|
|
180
|
-
optimizer = braintools.optim.Adam(lr=3e-3)
|
|
181
|
-
optimizer.register_trainable_weights(params)
|
|
182
|
-
|
|
183
|
-
def loss_fn():
|
|
184
|
-
logits = brainstate.transform.for_loop(net.update, inputs)
|
|
185
|
-
logits = u.math.mean(logits, axis=0)
|
|
186
|
-
return braintools.metric.softmax_cross_entropy_with_integer_labels(
|
|
187
|
-
logits,
|
|
188
|
-
labels,
|
|
189
|
-
).mean()
|
|
190
|
-
|
|
191
|
-
@brainstate.transform.jit
|
|
192
|
-
def train_step():
|
|
193
|
-
brainstate.nn.init_all_states(net, batch_size=batch_size)
|
|
194
|
-
grads, loss = brainstate.transform.grad(
|
|
195
|
-
loss_fn,
|
|
196
|
-
params,
|
|
197
|
-
return_value=True,
|
|
198
|
-
)()
|
|
199
|
-
optimizer.update(grads)
|
|
200
|
-
return loss
|
|
201
|
-
|
|
202
|
-
loss = train_step()
|
|
203
|
-
```
|
|
204
|
-
|
|
205
|
-
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.
|
|
206
|
-
|
|
207
|
-
## Reference routing
|
|
208
|
-
|
|
209
|
-
Open only the smallest reference that owns the decision.
|
|
210
|
-
|
|
211
|
-
### Training variation choices
|
|
212
|
-
|
|
213
|
-
| Reference | Open when |
|
|
214
|
-
|---|---|
|
|
215
|
-
| `references/braintools/data-preprocessing.md` | Encoding continuous values, events, or temporal features into time-major spike inputs before training |
|
|
216
|
-
| `references/braintools/parameter-initializer.md` | Selecting unit-aware parameter, weight, delay, variance-scaling, orthogonal, or spatial initialization |
|
|
217
|
-
| `references/braintools/surrogate.md` | Selecting a surrogate API style or gradient family, implementing a custom surrogate, or validating its gradient |
|
|
218
|
-
| `references/braintools/metric.md` | Selecting the training loss or evaluation metric and validating its input orientation, units, and reduction |
|
|
219
|
-
| `references/braintools/optimizer.md` | Selecting an optimizer, learning-rate scheduler, Optax bridge, SciPy optimizer, or Nevergrad optimizer |
|
|
220
|
-
| `references/braintools/brainstate-control-flow-patterns.md` | Choosing `for_loop` versus `scan`, adding transformed branches, or checkpointing a long differentiated rollout |
|
|
221
|
-
|
|
222
|
-
### Modeling variation choices
|
|
223
|
-
|
|
224
|
-
| Reference | Open when |
|
|
225
|
-
|---|---|
|
|
226
|
-
| `references/array-creation.md` | Constructing specialized unit-aware current ranges, grids, filled arrays, template-shaped arrays, or matrix patterns |
|
|
227
|
-
| `references/braintools/connectivity.md` | Selecting spatial, topological, biological E/I, kernel, or compartment-aware connection pairs and exporting a `ConnectionResult` to BrainEvent storage |
|
|
228
|
-
| `references/braintools/input-current.md` | Generating or composing direct unit-aware current sections, pulses, waveforms, or stochastic processes |
|
|
229
|
-
| `references/component-selection.md` | Choosing a neuron, synapse, synaptic output, plasticity model, input generator, or readout from the documented native API families |
|
|
230
|
-
| `references/projection-patterns.md` | Choosing projection alignment or API form, adding delays or short-term plasticity, using direct/delta projections, or adding gap junctions |
|
|
231
|
-
| `references/perturbation-experiment-validity.md` | Estimating baseline tuning or features before matched point-neuron perturbations, calibrating delivered target dose, or deciding whether activity and analysis support justify a formal causal run |
|
|
232
|
-
| `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 |
|
|
233
|
-
| `references/brainPy(legacy)/brainpy legacy workflow.md` | Use as the only first-level legacy entry when existing legacy `brainpy` has no BrainUnit, unit-aware, or BrainTrace code and the user explicitly requests it; this workflow routes all second-level legacy references |
|
|
234
|
-
| `skills/package-skills/brainevent/SKILL.md` | Selecting sparse event representations, connectivity formats, event operators, plasticity kernels, or custom kernels |
|
|
235
|
-
| `skills/package-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 |
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
## Application script examples
|
|
239
|
-
| Reference | Open when |
|
|
240
|
-
|---|---|
|
|
241
|
-
| `references/scripts/103_COBA_2005.py` | Needing a complete canonical E/I COBA network built from native BrainPy-State projections |
|
|
242
|
-
| `references/scripts/106_COBA_HH_2007.py` | Reproducing a conductance-based E/I network with a custom Hodgkin-Huxley neuron |
|
|
243
|
-
| `references/scripts/107_gamma_oscillation_1996.py` | Reproducing gamma oscillations with custom neuron and synapse dynamics |
|
|
244
|
-
| `references/scripts/109_fast_global_oscillation.py` | Needing a complete `DeltaProj` network with delayed recurrent input |
|
|
245
|
-
| `references/scripts/sound_localization.py` | Needing a mapped delay-line coincidence network with heterogeneous integer event taps and BrainEvent fixed fan-out |
|
|
246
|
-
| `references/scripts/201_surrogate_grad_lif_fashion_mnist.py` | Needing a complete real-data surrogate-gradient LIF training workflow |
|
|
247
|
-
| `references/scripts/training-snn.py` | Needing a complete runnable surrogate-gradient SNN training workflow |
|