brainx-skill 1.0.3 → 1.0.8
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/LICENSE +1 -1
- package/README.md +29 -64
- package/adapters/gemini.js +7 -0
- package/adapters/opencode.js +7 -0
- package/adapters/windsurf.js +7 -0
- package/{lib → installation/lib}/installer.js +8 -5
- package/manifest.json +7 -1
- package/package.json +25 -10
- package/skills/braincell/SKILL.md +182 -0
- package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
- package/skills/braincell/references/channel-library.md +170 -0
- package/skills/braincell/references/ion-library.md +154 -0
- package/skills/braincell/references/mixions-for-adaptation.md +81 -0
- package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
- package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
- package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
- package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
- package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
- package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
- package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
- package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
- package/skills/braincell/references/scripts/channel_ablation.py +61 -0
- package/skills/braincell/references/scripts/fi_curve.py +68 -0
- package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
- package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
- package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
- package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
- package/skills/braincell/references/solver-library-with-effects.md +188 -0
- package/skills/brainevent/SKILL.md +268 -0
- package/skills/brainevent/references/connectivity-variants.md +312 -0
- package/skills/brainevent/references/custom-operators-cpu.md +304 -0
- package/skills/brainevent/references/custom-operators-gpu.md +468 -0
- package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
- package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
- package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
- package/skills/brainevent/references/sparse-formats.md +182 -0
- package/skills/brainevent/references/synaptic-plasticity.md +285 -0
- package/skills/brainpy-state/SKILL.md +232 -0
- package/skills/brainpy-state/references/array-creation.md +158 -0
- package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
- package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
- package/skills/brainpy-state/references/braintools/metric.md +152 -0
- package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
- package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
- package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
- package/skills/brainpy-state/references/component-selection.md +273 -0
- package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
- package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
- package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
- package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
- package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
- package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
- package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
- package/skills/brainpy-state/references/projection-patterns.md +125 -0
- package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
- package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
- package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
- package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
- package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
- package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
- package/skills/brainstate/SKILL.md +399 -0
- package/skills/brainstate/agents/openai.yaml +4 -0
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
- package/skills/brainstate/references/collective_model_operations.md +195 -0
- package/skills/brainstate/references/extension_mechanisms.md +293 -0
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
- package/skills/brainstate/references/model-interop-and-migration.md +305 -0
- package/skills/brainstate/references/simulation-environment.md +117 -0
- package/skills/brainstate/references/size-inference-variations.md +279 -0
- package/skills/brainstate/references/state-graph-operations.md +216 -0
- package/skills/brainstate/references/state_collections_and_utilities.md +235 -0
- package/skills/brainstate/scripts/integrator_rnn.py +359 -0
- package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
- package/skills/brainstate/scripts/modern_cnn.py +73 -0
- package/skills/brainstate/scripts/resnet.py +130 -0
- package/skills/brainunit/SKILL.md +287 -0
- package/skills/brainunit/references/array-creation.md +158 -0
- package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
- package/skills/brainunit/references/array-mechanics.md +165 -0
- package/skills/brainunit/references/math-function-library.md +433 -0
- package/skills/brainunit/references/physical-constant-library.md +58 -0
- package/skills/brainunit/references/prefix-library.md +116 -0
- package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
- package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
- package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
- package/skills/brainx-general-guard/SKILL.md +153 -0
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
- package/skills/brainx-install/SKILL.md +2 -2
- package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
- /package/{bin → installation/bin}/brainx.js +0 -0
- /package/{lib → installation/lib}/adapter-transaction.js +0 -0
- /package/{lib → installation/lib}/bundle.js +0 -0
- /package/{lib → installation/lib}/cli.js +0 -0
- /package/{lib → installation/lib}/constants.js +0 -0
- /package/{lib → installation/lib}/hash.js +0 -0
- /package/{lib → installation/lib}/paths.js +0 -0
- /package/{lib → installation/lib}/prompts.js +0 -0
- /package/{lib → installation/lib}/receipt.js +0 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
# Copyright 2025 BrainX Ecosystem Limited. All Rights Reserved.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# ==============================================================================
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
import brainevent
|
|
18
|
+
import matplotlib.pyplot as plt
|
|
19
|
+
import numpy as np
|
|
20
|
+
from jax import vmap
|
|
21
|
+
from scipy.io import loadmat
|
|
22
|
+
|
|
23
|
+
import brainpy as bp
|
|
24
|
+
import brainpy.math as bm
|
|
25
|
+
from brainpy import neurons
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class MultiAreaNet(bp.Network):
|
|
29
|
+
def __init__(
|
|
30
|
+
self, hier, conn, delay_mat, muIE=0.0475, muEE=.0375, wII=.075,
|
|
31
|
+
wEE=.01, wIE=.075, wEI=.0375, extE=15.4, extI=14.0, alpha=4., seed=None,
|
|
32
|
+
):
|
|
33
|
+
super(MultiAreaNet, self).__init__()
|
|
34
|
+
|
|
35
|
+
# data
|
|
36
|
+
self.hier = hier
|
|
37
|
+
self.conn = conn
|
|
38
|
+
self.delay_mat = delay_mat
|
|
39
|
+
|
|
40
|
+
# parameters
|
|
41
|
+
self.muIE = muIE
|
|
42
|
+
self.muEE = muEE
|
|
43
|
+
self.wII = wII
|
|
44
|
+
self.wEE = wEE
|
|
45
|
+
self.wIE = wIE
|
|
46
|
+
self.wEI = wEI
|
|
47
|
+
self.extE = extE
|
|
48
|
+
self.extI = extI
|
|
49
|
+
self.alpha = alpha
|
|
50
|
+
num_area = hier.size
|
|
51
|
+
self.num_area = num_area
|
|
52
|
+
|
|
53
|
+
# neuron models
|
|
54
|
+
self.E = neurons.LIF((num_area, 1600),
|
|
55
|
+
V_th=-50., V_reset=-60.,
|
|
56
|
+
V_rest=-70., tau=20., tau_ref=2.,
|
|
57
|
+
noise=3. / bm.sqrt(20.),
|
|
58
|
+
V_initializer=bp.init.Uniform(-70., -50.),
|
|
59
|
+
method='exp_auto',
|
|
60
|
+
keep_size=True,
|
|
61
|
+
ref_var=True)
|
|
62
|
+
self.I = neurons.LIF((num_area, 400), V_th=-50., V_reset=-60.,
|
|
63
|
+
V_rest=-70., tau=10., tau_ref=2., noise=3. / bm.sqrt(10.),
|
|
64
|
+
V_initializer=bp.init.Uniform(-70., -50.),
|
|
65
|
+
method='exp_auto',
|
|
66
|
+
keep_size=True,
|
|
67
|
+
ref_var=True)
|
|
68
|
+
|
|
69
|
+
# delays
|
|
70
|
+
self.intra_delay_step = int(2. / bm.get_dt())
|
|
71
|
+
self.E_delay_steps = bm.asarray(delay_mat.T / bm.get_dt(), dtype=int)
|
|
72
|
+
bm.fill_diagonal(self.E_delay_steps, self.intra_delay_step)
|
|
73
|
+
self.Edelay = bm.LengthDelay(self.E.spike, delay_len=int(self.E_delay_steps.max()))
|
|
74
|
+
self.Idelay = bm.LengthDelay(self.I.spike, delay_len=self.intra_delay_step)
|
|
75
|
+
|
|
76
|
+
# synapses from I
|
|
77
|
+
self.intra_I2E_w = -wEI
|
|
78
|
+
self.intra_I2I_w = -wII
|
|
79
|
+
self.intra_I2I_seed = np.random.randint(0, 10000, num_area)
|
|
80
|
+
self.intra_I2E_seed = np.random.randint(0, 10000, num_area)
|
|
81
|
+
|
|
82
|
+
# synapses from E
|
|
83
|
+
self.E2E_seed = np.random.randint(0, 10000, (num_area, num_area))
|
|
84
|
+
self.E2I_seed = np.random.randint(0, 10000, (num_area, num_area))
|
|
85
|
+
self.E2E_weights = (1 + alpha * hier) * muEE * conn.T # inter-area connections
|
|
86
|
+
# intra-area connections
|
|
87
|
+
self.E2E_weights = bm.fill_diagonal(self.E2E_weights, (1 + alpha * hier) * wEE, inplace=False)
|
|
88
|
+
self.E2I_weights = (1 + alpha * hier) * muIE * conn.T # inter-area connections
|
|
89
|
+
# intra-area connections
|
|
90
|
+
self.E2I_weights = bm.fill_diagonal(self.E2I_weights, (1 + alpha * hier) * wIE, inplace=False)
|
|
91
|
+
|
|
92
|
+
def update(self, v1_input):
|
|
93
|
+
self.E.input[0] += v1_input
|
|
94
|
+
self.E.input += self.extE
|
|
95
|
+
self.I.input += self.extI
|
|
96
|
+
E_not_ref = bm.logical_not(self.E.refractory)
|
|
97
|
+
I_not_ref = bm.logical_not(self.I.refractory)
|
|
98
|
+
|
|
99
|
+
# synapses from E
|
|
100
|
+
f_E2E = vmap(lambda spk, weight, seed: brainevent.BinaryArray(spk) @ brainevent.JITCScalarC((weight, 0.1, seed), shape=(1600, 1600)))
|
|
101
|
+
f_E2I = vmap(lambda spk, weight, seed: brainevent.BinaryArray(spk) @ brainevent.JITCScalarC((weight, 0.1, seed), shape=(1600, 400)))
|
|
102
|
+
for i in range(self.num_area):
|
|
103
|
+
delayed_E_spikes = self.Edelay(self.E_delay_steps[i], i)
|
|
104
|
+
self.E.V += f_E2E(delayed_E_spikes, self.E2E_weights[i], self.E2E_seed[i]) * E_not_ref # E2E
|
|
105
|
+
self.I.V += f_E2I(delayed_E_spikes, self.E2I_weights[i], self.E2I_seed[i]) * I_not_ref # E2I
|
|
106
|
+
|
|
107
|
+
# synapses from I
|
|
108
|
+
delayed_I_spikes = self.Idelay(self.intra_delay_step)
|
|
109
|
+
f_I2E = vmap(lambda spk, seed: brainevent.BinaryArray(spk) @ brainevent.JITCScalarC((self.intra_I2E_w, 0.1, seed), shape=(400, 1600)))
|
|
110
|
+
self.E.V += f_I2E(delayed_I_spikes, self.intra_I2E_seed) * E_not_ref # I2E
|
|
111
|
+
f_I2I = vmap(lambda spk, seed: brainevent.BinaryArray(spk) @ brainevent.JITCScalarC((self.intra_I2I_w, 0.1, seed), shape=(400, 400)))
|
|
112
|
+
self.I.V += f_I2I(delayed_I_spikes, self.intra_I2I_seed) * I_not_ref # I2I
|
|
113
|
+
|
|
114
|
+
# updates
|
|
115
|
+
self.Edelay.update(self.E.spike)
|
|
116
|
+
self.Idelay.update(self.I.spike)
|
|
117
|
+
self.E.update()
|
|
118
|
+
self.I.update()
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def raster_plot(xValues, yValues, duration):
|
|
122
|
+
ticks = np.round(np.arange(0, 29) + 0.5, 2)
|
|
123
|
+
areas = ['V1', 'V2', 'V4', 'DP', 'MT', '8m', '5', '8l', 'TEO', '2', 'F1',
|
|
124
|
+
'STPc', '7A', '46d', '10', '9/46v', '9/46d', 'F5', 'TEpd', 'PBr',
|
|
125
|
+
'7m', '7B', 'F2', 'STPi', 'PROm', 'F7', '8B', 'STPr', '24c']
|
|
126
|
+
N = len(ticks)
|
|
127
|
+
plt.figure(figsize=(8, 6))
|
|
128
|
+
plt.plot(xValues, yValues / (4 * 400), '.', markersize=1)
|
|
129
|
+
plt.plot([0, duration], np.arange(N + 1).repeat(2).reshape(-1, 2).T, 'k-')
|
|
130
|
+
plt.ylabel('Area')
|
|
131
|
+
plt.yticks(np.arange(N))
|
|
132
|
+
plt.xlabel('Time [ms]')
|
|
133
|
+
plt.ylim(0, N)
|
|
134
|
+
plt.yticks(ticks, areas)
|
|
135
|
+
plt.xlim(0, duration)
|
|
136
|
+
plt.tight_layout()
|
|
137
|
+
plt.show()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# hierarchy values
|
|
141
|
+
hierVals = loadmat('../Joglekar_2018_data/hierValspython.mat')
|
|
142
|
+
hierValsnew = hierVals['hierVals'].flatten()
|
|
143
|
+
hier = bm.asarray(hierValsnew / max(hierValsnew)) # hierarchy normalized.
|
|
144
|
+
|
|
145
|
+
# fraction of labeled neurons
|
|
146
|
+
flnMatp = loadmat('../Joglekar_2018_data/efelenMatpython.mat')
|
|
147
|
+
conn = bm.asarray(flnMatp['flnMatpython'].squeeze()) # fln values..Cij is strength from j to i
|
|
148
|
+
|
|
149
|
+
# Distance
|
|
150
|
+
speed = 3.5 # axonal conduction velocity
|
|
151
|
+
distMatp = loadmat('../Joglekar_2018_data/subgraphWiring29.mat')
|
|
152
|
+
distMat = distMatp['wiring'].squeeze() # distances between areas values..
|
|
153
|
+
delayMat = bm.asarray(distMat / speed)
|
|
154
|
+
|
|
155
|
+
pars = dict(extE=14.2, extI=14.7, wII=.075, wEE=.01, wIE=.075, wEI=.0375, muEE=.0375, muIE=0.0475)
|
|
156
|
+
inps = dict(value=15, duration=150)
|
|
157
|
+
|
|
158
|
+
inputs, length = bp.inputs.section_input(values=[0, inps['value'], 0.],
|
|
159
|
+
durations=[300., inps['duration'], 500],
|
|
160
|
+
return_length=True)
|
|
161
|
+
|
|
162
|
+
net = MultiAreaNet(hier, conn, delayMat, **pars)
|
|
163
|
+
runner = bp.DSRunner(net, monitors={'E.spike': lambda: net.E.spike.flatten()})
|
|
164
|
+
runner.run(inputs=inputs)
|
|
165
|
+
|
|
166
|
+
times, indices = np.where(runner.mon['E.spike'])
|
|
167
|
+
times = runner.mon.ts[times]
|
|
168
|
+
raster_plot(times, indices, length)
|
|
@@ -0,0 +1,356 @@
|
|
|
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)
|