brainx-skill 1.0.6 → 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.
Files changed (91) hide show
  1. package/README.md +9 -2
  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 +5 -1
  7. package/package.json +7 -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 +210 -0
  11. package/skills/braincell/references/channel-library.md +170 -0
  12. package/skills/braincell/references/ion-library.md +154 -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 +162 -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 +121 -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/brainpy-state/SKILL.md +232 -0
  40. package/skills/brainpy-state/references/array-creation.md +158 -0
  41. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  42. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  43. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  44. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  45. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  46. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  47. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  48. package/skills/brainpy-state/references/component-selection.md +273 -0
  49. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  50. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  51. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  52. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  53. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  54. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  55. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  56. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  57. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  58. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  59. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  60. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  61. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  62. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  63. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  64. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  65. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  66. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  67. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  68. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  69. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  70. package/skills/brainstate/SKILL.md +1 -1
  71. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
  72. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
  73. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
  74. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
  75. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
  76. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
  77. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
  78. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
  79. package/skills/brainstate/references/collective_model_operations.md +9 -9
  80. package/skills/brainstate/references/extension_mechanisms.md +12 -1
  81. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
  82. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
  83. package/skills/brainstate/references/model-interop-and-migration.md +11 -1
  84. package/skills/brainstate/references/size-inference-variations.md +11 -0
  85. package/skills/brainstate/references/state-graph-operations.md +13 -15
  86. package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
  87. package/skills/brainx-general-guard/SKILL.md +153 -0
  88. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
  89. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
  90. package/skills/brainstate/references/braintools-optimizer-reference.md +0 -133
  91. package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
@@ -0,0 +1,147 @@
1
+ # examples/nest_like/evaluate_tsodyks2_synapse.py
2
+ # Copyright 2026 BrainX Ecosystem Limited. Apache 2.0.
3
+ """Tsodyks-2 short-term plasticity -- NEST-style port.
4
+
5
+ Port of NEST's ``evaluate_tsodyks2_synapse.py``. A regular presynaptic spike burst
6
+ (plus a recovery pair) drives a single ``tsodyks2_synapse`` edge onto a linear,
7
+ never-spiking ``iaf_psc_exp`` post neuron (``V_th = 1e4`` mV, ``tau_syn_ex = 3 ms``);
8
+ the post membrane potential **is** the PSC-amplitude train, carrying the depression
9
+ or facilitation envelope. Two regimes are shown:
10
+
11
+ * depression ``U=0.67, tau_rec=450 ms, tau_fac=0`` -- EPSP peaks shrink
12
+ * facilitation ``U=0.1, tau_rec=100 ms, tau_fac=1000`` -- EPSP peaks grow
13
+
14
+ Plastic synapses cannot be driven by a device in NEST (a ``parrot_neuron`` relays
15
+ the train); on the ``Simulator`` API a ``spike_generator`` drives the plastic edge
16
+ directly. Parameters follow ``pynest/examples/evaluate_tsodyks2_synapse.py`` and the
17
+ cluster-01 STP parity drive. ``tsodyks2_synapse`` delivers ``w_eff = x*u*weight``.
18
+
19
+ Run: python examples/nest_like/evaluate_tsodyks2_synapse.py
20
+ """
21
+ import jax
22
+ import brainstate
23
+ jax.config.update('jax_enable_x64', True)
24
+ brainstate.environ.set(precision=64)
25
+
26
+ import braintools
27
+ import numpy as np
28
+ import brainunit as u
29
+
30
+ from brainpy.state import (Simulator, iaf_psc_exp, spike_generator, multimeter,
31
+ tsodyks2_synapse)
32
+
33
+ #: Resolution (ms).
34
+ DT = 0.1
35
+ #: 50 ms-ISI burst then a recovery pair (cluster-01 STP protocol), in ms.
36
+ TRAIN = [50., 100., 150., 200., 250., 300., 350., 400., 650., 700.]
37
+ #: Simulation horizon (ms).
38
+ T_SIM = 800.0
39
+ #: Per-edge weight (pA).
40
+ WEIGHT = 250.0
41
+ #: The two STP regimes (Tsodyks et al. parameters, upstream values).
42
+ REGIMES = {
43
+ "depression": dict(U=0.67, u=0.67, x=1.0, tau_rec=450.0, tau_fac=0.0),
44
+ "facilitation": dict(U=0.1, u=0.1, x=1.0, tau_rec=100.0, tau_fac=1000.0),
45
+ }
46
+
47
+
48
+ def _post(sim):
49
+ """Build the linear, never-spiking ``iaf_psc_exp`` post (V_m == PSC train)."""
50
+ return sim.create(
51
+ iaf_psc_exp, 1, C_m=250. * u.pF, tau_m=20. * u.ms,
52
+ tau_syn_ex=3. * u.ms, tau_syn_in=3. * u.ms, t_ref=2. * u.ms,
53
+ E_L=0. * u.mV, V_reset=0. * u.mV, V_th=1e4 * u.mV,
54
+ V_initializer=braintools.init.Constant(0. * u.mV))
55
+
56
+
57
+ def run(regime="depression", weight=WEIGHT, train=TRAIN, t_sim=T_SIM):
58
+ """Drive one ``tsodyks2_synapse`` edge with the burst-and-recovery protocol.
59
+
60
+ Parameters
61
+ ----------
62
+ regime : {"depression", "facilitation"}, optional
63
+ Which STP regime's parameters to use. Default ``"depression"``.
64
+ weight : float, optional
65
+ Per-edge weight (pA). Default :data:`WEIGHT`.
66
+ train : sequence of float, optional
67
+ Presynaptic spike times (ms). Default :data:`TRAIN`.
68
+ t_sim : float, optional
69
+ Simulation horizon (ms). Default :data:`T_SIM`.
70
+
71
+ Returns
72
+ -------
73
+ times : numpy.ndarray
74
+ Recorder time axis (ms).
75
+ vm : numpy.ndarray
76
+ Post membrane potential (mV) -- the PSC-amplitude train.
77
+ """
78
+ p = REGIMES[regime]
79
+ sim = Simulator(dt=DT * u.ms)
80
+ post = _post(sim)
81
+ sg = sim.create(spike_generator, spike_times=np.asarray(train) * u.ms)
82
+ sim.connect(sg, post, synapse=tsodyks2_synapse(
83
+ weight=weight * u.pA, U=p["U"], u=p["u"], x=p["x"],
84
+ tau_rec=p["tau_rec"] * u.ms, tau_fac=p["tau_fac"] * u.ms))
85
+ mm = sim.create(multimeter, record_from=["V_m"], interval=DT * u.ms)
86
+ sim.connect(mm, post) # reversed: the multimeter observes the neuron
87
+ res = sim.simulate(t_sim * u.ms)
88
+ times = np.asarray(u.get_mantissa(res.times / u.ms))
89
+ vm = np.asarray(u.get_mantissa(res.trace(mm, "V_m") / u.mV)).reshape(-1)
90
+ return times, vm
91
+
92
+
93
+ def burst_peak_ratio(vm, train=TRAIN, dt=DT):
94
+ """Ratio of the last to first EPSP peak across the initial burst.
95
+
96
+ A crude depression/facilitation indicator: ``< 1`` for depression (peaks
97
+ shrink), ``> 1`` for facilitation (peaks grow). The peak after spike ``k`` is
98
+ sampled a few ms after the spike (EPSP rise), within the 50 ms-ISI burst.
99
+
100
+ Parameters
101
+ ----------
102
+ vm : numpy.ndarray
103
+ Post V_m trace (mV).
104
+ train : sequence of float, optional
105
+ Presynaptic spike times (ms).
106
+ dt : float, optional
107
+ Resolution (ms).
108
+
109
+ Returns
110
+ -------
111
+ float
112
+ ``peak_last / peak_first`` over the eight-spike burst.
113
+ """
114
+ burst = [t for t in train if t <= 400.0]
115
+ peaks = []
116
+ for t in burst:
117
+ lo, hi = int(round(t / dt)), int(round((t + 40.0) / dt))
118
+ peaks.append(float(np.max(vm[lo:hi])))
119
+ return peaks[-1] / peaks[0]
120
+
121
+
122
+ def main():
123
+ print("Tsodyks-2 STP (brainpy.state, iaf_psc_exp post, V_m = PSC train)")
124
+ traces = {}
125
+ for regime in REGIMES:
126
+ t, v = run(regime)
127
+ traces[regime] = (t, v)
128
+ ratio = burst_peak_ratio(v)
129
+ print(f" {regime:12s}: V_m max {v.max():.3f} mV, last/first burst peak {ratio:.3f}")
130
+
131
+ try:
132
+ import matplotlib.pyplot as plt
133
+ plt.figure(figsize=(8, 4))
134
+ for regime, c in (("depression", "C0"), ("facilitation", "C1")):
135
+ t, v = traces[regime]
136
+ plt.plot(t, v, c, label=regime)
137
+ plt.xlabel("time (ms)"); plt.ylabel("V_m (mV)")
138
+ plt.title("tsodyks2_synapse -- depression vs facilitation")
139
+ plt.legend(); plt.tight_layout()
140
+ plt.savefig("examples/nest_like/evaluate_tsodyks2_synapse.png", dpi=100)
141
+ print(" wrote examples/nest_like/evaluate_tsodyks2_synapse.png")
142
+ except ImportError:
143
+ print(" (matplotlib not installed; skipping plot)")
144
+
145
+
146
+ if __name__ == "__main__":
147
+ main()
@@ -0,0 +1,112 @@
1
+ # examples/nest_like/spatial_gaussex.py
2
+ """Spatial networks: a Gaussian probabilistic kernel -- NEST ``spatial/gaussex.py`` port.
3
+
4
+ Creates two ``iaf_psc_alpha`` populations on a shared grid and connects them with a
5
+ distance-dependent pairwise-Bernoulli rule whose probability is a Gaussian of the
6
+ source->target distance,
7
+
8
+ .. math:: p(d) = \\exp\\!\\big(-d^2 / (2\\,\\mathrm{std}^2)\\big),
9
+
10
+ clipped to a circular mask of ``radius``. This is
11
+ ``spatial.spatial_pairwise_bernoulli(p=spatial.gaussian(spatial.distance, std=...),
12
+ mask=spatial.circular(...))`` riding the ordinary :meth:`~brainpy.state.Simulator.connect`
13
+ -- the same call any non-spatial rule uses. The realized footprint of the central source
14
+ neuron is read back with :func:`~brainpy.state.spatial.target_positions` (NEST
15
+ ``GetTargetPositions``).
16
+
17
+ The per-distance connection probability is a fixed law, so the validation
18
+ (``brainpy_state/_nest_validation/spatial_gaussian_kernel_test.py``) asserts the empirical
19
+ ``p(d)`` follows the Gaussian (NEST-free) and matches live NEST's empirical curve within a
20
+ distributional band (PRNG draws diverge sample-by-sample; the law does not).
21
+
22
+ Run: PYTHONPATH=. python examples/nest_like/spatial_gaussex.py
23
+ """
24
+ import jax
25
+ import brainstate
26
+
27
+ jax.config.update('jax_enable_x64', True)
28
+ brainstate.environ.set(precision=64)
29
+
30
+ import numpy as np
31
+ import brainunit as u
32
+
33
+ from brainpy import state as bp
34
+
35
+
36
+ def run(shape=(30, 30), extent=(3.0, 3.0), std=0.5, radius=3.0, seed=0):
37
+ """Connect two grid layers with a Gaussian kernel; return the central footprint.
38
+
39
+ Parameters
40
+ ----------
41
+ shape : tuple of int, optional
42
+ ``(n_columns, n_rows)`` of the shared grid. Default ``(30, 30)`` (NEST's value).
43
+ extent : tuple of float, optional
44
+ Physical extent (micrometres). Default ``(3.0, 3.0)``.
45
+ std : float, optional
46
+ Gaussian kernel standard deviation (micrometres). Default ``0.5``.
47
+ radius : float, optional
48
+ Circular-mask cutoff radius (micrometres). Default ``3.0``.
49
+ seed : int, optional
50
+ Connectivity-sampling seed. Default ``0``.
51
+
52
+ Returns
53
+ -------
54
+ coords : brainunit.Quantity
55
+ ``(n, 2)`` node coordinates of the (shared) grid.
56
+ ctr : int
57
+ Local index of the central source node.
58
+ target_pos : brainunit.Quantity
59
+ ``(k, 2)`` coordinates of the central node's realized targets.
60
+
61
+ Examples
62
+ --------
63
+ .. code-block:: python
64
+
65
+ >>> coords, ctr, tgt = run(shape=(10, 10))
66
+ >>> coords.shape
67
+ (100, 2)
68
+ >>> bool(tgt.shape[0] >= 1) # the centre connects to at least itself-at-distance-0
69
+ True
70
+ """
71
+ sim = bp.Simulator(dt=0.1 * u.ms)
72
+ pos = bp.spatial.grid(list(shape), extent=list(extent))
73
+ a = sim.create(bp.iaf_psc_alpha, positions=pos)
74
+ b = sim.create(bp.iaf_psc_alpha, positions=pos)
75
+ sim.connect(
76
+ a, b,
77
+ rule=bp.spatial.spatial_pairwise_bernoulli(
78
+ p=bp.spatial.gaussian(bp.spatial.distance, std=std),
79
+ mask=bp.spatial.circular(radius)),
80
+ weight=1.0 * u.pA, delay=1.0 * u.ms, seed=seed)
81
+ ctr = bp.spatial.center_element(pos)
82
+ target_pos = bp.spatial.target_positions(sim, a[ctr], b)[0]
83
+ return sim.get_position(a), ctr, target_pos
84
+
85
+
86
+ def main():
87
+ coords, ctr, target_pos = run()
88
+ xy = np.asarray(u.get_magnitude(coords.to(u.um)))
89
+ tgt = np.asarray(u.get_magnitude(target_pos.to(u.um)))
90
+ print('spatial_gaussex (brainpy.state)')
91
+ print(f' {xy.shape[0]} nodes; centre node {ctr} has {tgt.shape[0]} realized targets')
92
+ try:
93
+ import matplotlib.pyplot as plt
94
+ except ImportError:
95
+ print(' (matplotlib not installed; skipping plot)')
96
+ return
97
+ plt.figure(figsize=(5, 5))
98
+ plt.scatter(xy[:, 0], xy[:, 1], s=8, color='0.8', label='all nodes')
99
+ plt.scatter(tgt[:, 0], tgt[:, 1], s=20, color='green', label='targets')
100
+ plt.scatter([xy[ctr, 0]], [xy[ctr, 1]], s=80, color='blue', label='source')
101
+ plt.gca().set_aspect('equal', 'box')
102
+ plt.axis([-2.0, 2.0, -2.0, 2.0])
103
+ plt.grid(True)
104
+ plt.legend(loc='upper right')
105
+ plt.title('Connection targets, Gaussian kernel (brainpy.state)')
106
+ plt.tight_layout()
107
+ plt.savefig('examples/nest_like/spatial_gaussex.png', dpi=100)
108
+ print(' wrote examples/nest_like/spatial_gaussex.png')
109
+
110
+
111
+ if __name__ == '__main__':
112
+ main()
@@ -0,0 +1,198 @@
1
+ # examples/nest_like/synapsecollection.py
2
+ # Copyright 2026 BrainX Ecosystem Limited. Apache 2.0.
3
+ r"""SynapseCollection introspection tour — NEST-style port.
4
+
5
+ Ports NEST's ``pynest/examples/synapsecollection.py`` to the Simulator API. The
6
+ upstream connects neurons under several rules / synapse models / weight
7
+ distributions, retrieves the connections with ``nest.GetConnections()`` (a
8
+ ``SynapseCollection``), and reads / sets ``.source``, ``.target``, ``.weight`` to
9
+ build weight matrices. This port reproduces every idiom with
10
+ :meth:`Simulator.get_connections` and
11
+ :class:`~brainpy.state.SynapseCollection`:
12
+
13
+ * ``get(['source', 'target', 'weight'])`` — read several attributes at once;
14
+ * ``set('weight', values)`` — per-edge write-back, round-tripped through ``get``;
15
+ * ``get_connections()`` — every edge; ``get_connections(src, tgt)`` — a
16
+ source/target slice; ``get_connections(synapse=model)`` — one synapse model.
17
+
18
+ Three faithful adaptations to ``brainpy.state``:
19
+
20
+ * **one_to_one is per-edge here.** NEST's ``one_to_one`` uses the per-edge-settable
21
+ default ``static_synapse``; the homogeneous ``one_to_one`` *EventProjection*
22
+ shares a single scalar, so to keep the upstream's *per-edge* weight set we route
23
+ the ``one_to_one`` block through the per-edge ``static_synapse`` plastic path
24
+ (same realized connectivity, per-edge weights).
25
+ * **Distributional weights are sampled at connect on the static path.** The
26
+ ``all_to_all`` block draws ``Uniform(0.5, 4.5)`` pA with the ``dist`` API (the
27
+ brainpy.state ``Parameter`` analogue, sampled once at ``connect``). The plastic
28
+ ``stdp_synapse`` connects take a concrete initial weight (the rule evolves it
29
+ during ``simulate``), so the complex block uses fixed initial weights there.
30
+ * **Population-local indices.** ``source`` / ``target`` index within their
31
+ population (no global node-id space), so the matrices are indexed directly.
32
+
33
+ The demo is pure introspection — it never calls ``simulate()``.
34
+
35
+ Run: PYTHONPATH=. python examples/nest_like/synapsecollection.py
36
+ """
37
+ import jax
38
+ import brainstate
39
+ jax.config.update('jax_enable_x64', True)
40
+ brainstate.environ.set(precision=64)
41
+
42
+ import numpy as np
43
+ import brainunit as u
44
+
45
+ from brainpy.state import (Simulator, iaf_psc_alpha, one_to_one, all_to_all,
46
+ pairwise_bernoulli, fixed_total_number, fixed_indegree,
47
+ static_synapse, stdp_synapse)
48
+ from brainpy.state import dist
49
+
50
+ DT = 0.1 # resolution [ms]
51
+
52
+
53
+ def ramp_weights(n):
54
+ """NEST's ``[{'weight': x} for x in range(1, n+1)]`` as a pA array ``[1..n]``."""
55
+ return np.arange(1, n + 1, dtype=float) * u.pA
56
+
57
+
58
+ def collection_arrays(conns):
59
+ """Read a SynapseCollection into ``(sources, targets, weights_pA, matrix)``.
60
+
61
+ Parameters
62
+ ----------
63
+ conns : SynapseCollection
64
+ The connections to read.
65
+
66
+ Returns
67
+ -------
68
+ sources, targets : numpy.ndarray
69
+ Population-local source / target index per edge.
70
+ weights : numpy.ndarray
71
+ Per-edge weight in pA.
72
+ matrix : numpy.ndarray
73
+ Dense ``(max_src+1, max_tgt+1)`` weight matrix (``W[src, tgt] += w``); a
74
+ ``(0, 0)`` array when the collection is empty.
75
+ """
76
+ g = conns.get(['source', 'target', 'weight'])
77
+ srcs = np.asarray(g['source'])
78
+ tgts = np.asarray(g['target'])
79
+ weights = np.asarray(u.Quantity(g['weight']).to_decimal(u.pA))
80
+ if srcs.size == 0:
81
+ return srcs, tgts, weights, np.zeros((0, 0))
82
+ M = np.zeros((int(srcs.max()) + 1, int(tgts.max()) + 1))
83
+ np.add.at(M, (srcs, tgts), weights)
84
+ return srcs, tgts, weights, M
85
+
86
+
87
+ def build_one_to_one(n=10):
88
+ """``n`` neurons wired one-to-one with a per-edge ``static_synapse``.
89
+
90
+ Returns ``(sim, nrns)``. The connection is the per-edge ``static_synapse``
91
+ plastic path (not the homogeneous ``one_to_one`` EventProjection), so the
92
+ upstream's per-edge weight ``set`` round-trips.
93
+ """
94
+ sim = Simulator(dt=DT * u.ms)
95
+ nrns = sim.create(iaf_psc_alpha, n)
96
+ sim.connect(nrns, nrns, rule=one_to_one,
97
+ synapse=static_synapse(weight=1. * u.pA))
98
+ return sim, nrns
99
+
100
+
101
+ def build_all_to_all(n_pre=10, n_post=5, seed=0):
102
+ """``n_pre -> n_post`` all-to-all with ``Uniform(0.5, 4.5)`` pA weights.
103
+
104
+ Returns ``(sim, pre, post)``. Weights are drawn once at ``connect`` from the
105
+ ``dist`` Parameter API (the static path samples distributions eagerly).
106
+ """
107
+ sim = Simulator(dt=DT * u.ms)
108
+ pre = sim.create(iaf_psc_alpha, n_pre)
109
+ post = sim.create(iaf_psc_alpha, n_post)
110
+ sim.connect(pre, post, rule=all_to_all,
111
+ weight=dist.Uniform(0.5 * u.pA, 4.5 * u.pA), comm='sparse', seed=seed)
112
+ return sim, pre, post
113
+
114
+
115
+ def build_complex(n=15, seed=0):
116
+ """``n`` neurons wired with five rules / models (the upstream's complex case).
117
+
118
+ Returns ``(sim, nrns)``. Mirrors NEST's five ``Connect`` calls: a
119
+ ``one_to_one`` ``stdp_synapse``, a ``pairwise_bernoulli`` static block, a
120
+ ``fixed_total_number`` static block, an ``all_to_all`` ``stdp_synapse``, and a
121
+ ``fixed_indegree`` static block.
122
+ """
123
+ sim = Simulator(dt=DT * u.ms)
124
+ nrns = sim.create(iaf_psc_alpha, n)
125
+ sim.connect(nrns[:5], nrns[:5], rule=one_to_one,
126
+ synapse=stdp_synapse(weight=5. * u.pA))
127
+ sim.connect(nrns[:10], nrns[5:12], rule=pairwise_bernoulli(0.4),
128
+ weight=4. * u.pA, comm='sparse', seed=seed)
129
+ sim.connect(nrns[5:10], nrns[:5], rule=fixed_total_number(5),
130
+ weight=3. * u.pA, comm='sparse', seed=seed)
131
+ sim.connect(nrns[10:], nrns[:12], rule=all_to_all,
132
+ synapse=stdp_synapse(weight=4. * u.pA))
133
+ sim.connect(nrns, nrns[12:], rule=fixed_indegree(3),
134
+ weight=1. * u.pA, comm='sparse', seed=seed)
135
+ return sim, nrns
136
+
137
+
138
+ def main():
139
+ print("synapsecollection: SynapseCollection introspection tour (brainpy.state)")
140
+
141
+ # 1. one_to_one: identity, then a per-edge weight set.
142
+ sim, nrns = build_one_to_one(10)
143
+ conns = sim.get_connections()
144
+ srcs, tgts, w0, _ = collection_arrays(conns)
145
+ print(f" one_to_one : {len(conns)} edges, identity={np.array_equal(srcs, tgts)}, "
146
+ f"uniform weight={np.unique(w0).tolist()} pA")
147
+ conns.set('weight', ramp_weights(10))
148
+ w1 = np.asarray(u.Quantity(conns.get('weight')).to_decimal(u.pA))
149
+ print(f" one_to_one : after set, diagonal weights={w1.tolist()} pA")
150
+
151
+ # 2. all_to_all with uniformly distributed weights, asymmetric sizes.
152
+ sim, pre, post = build_all_to_all(10, 5)
153
+ conns = sim.get_connections()
154
+ _, _, w, _ = collection_arrays(conns)
155
+ print(f" all_to_all : {len(conns)} edges, weight in "
156
+ f"[{w.min():.2f}, {w.max():.2f}] pA (Uniform 0.5..4.5)")
157
+
158
+ # 3. complex: five rules/models; query all / a subset / one model / set a subset.
159
+ sim, nrns = build_complex(15)
160
+ all_conns = sim.get_connections()
161
+ subset = sim.get_connections(source=nrns[:10], target=nrns[:10])
162
+ stdp = sim.get_connections(synapse='stdp_synapse')
163
+ ftn = sim.get_connections(source=nrns[5:10], target=nrns[:5])
164
+ print(f" complex : all={len(all_conns)} edges, "
165
+ f"first-ten subset={len(subset)}, stdp_synapse={len(stdp)}, "
166
+ f"fixed_total_number={len(ftn)}")
167
+ ftn.set('weight', ramp_weights(len(ftn)))
168
+ fw = np.asarray(u.Quantity(ftn.get('weight')).to_decimal(u.pA))
169
+ print(f" complex : fixed_total_number after set, weights={fw.tolist()} pA")
170
+
171
+ try:
172
+ import matplotlib.pyplot as plt
173
+
174
+ def _plot(ax, conns, title):
175
+ _srcs, _tgts, _weights, M = collection_arrays(conns)
176
+ if M.size:
177
+ im = ax.imshow(M, aspect="auto")
178
+ fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
179
+ ax.set_xlabel("target")
180
+ ax.set_ylabel("source")
181
+ ax.set_title(title)
182
+
183
+ fig, axes = plt.subplots(2, 2, figsize=(12, 10))
184
+ _plot(axes[0, 0], sim.get_connections(), "All connections")
185
+ _plot(axes[0, 1], sim.get_connections(source=nrns[:10], target=nrns[:10]),
186
+ "First ten neurons")
187
+ _plot(axes[1, 0], sim.get_connections(synapse='stdp_synapse'),
188
+ "stdp_synapse only")
189
+ _plot(axes[1, 1], ftn, "fixed_total_number, set weight")
190
+ fig.tight_layout()
191
+ fig.savefig("examples/nest_like/synapsecollection.png", dpi=100)
192
+ print(" wrote examples/nest_like/synapsecollection.png")
193
+ except ImportError:
194
+ print(" (matplotlib not installed; skipping plot)")
195
+
196
+
197
+ if __name__ == "__main__":
198
+ main()
@@ -0,0 +1,153 @@
1
+ # Synapse and connectivity
2
+
3
+ Use this reference when selecting a NEST-compatible synapse or plasticity rule, choosing canonical connectivity, constructing a unitful synapse spec, or reading and writing realized edges. Use `references/nest-compatible/network-building.md` for the complete connection-rule and projection-class map, and `references/nest-compatible/divergence-and-parity.md` for STDP parameter relocation and numerical bands.
4
+
5
+ ## Connection rules
6
+
7
+ Use these APIs to choose realized source-target pairs; choose the synapse spec separately to define what each realized edge does.
8
+
9
+ | API | Use when |
10
+ |---|---|
11
+ | `bp.all_to_all` | Use when every source must connect to every target, including the default generator fan-out. |
12
+ | `bp.one_to_one` | Use when source `i` must connect to target `i`; source and target views must have equal-size pairings. |
13
+ | `bp.fixed_indegree(k)` | Use when every target must receive exactly `k` randomly drawn presynaptic edges. |
14
+ | `bp.spatial.spatial_pairwise_bernoulli(p, mask=None, allow_autapses=True)` | Use when connection probability or eligibility depends on distance. |
15
+
16
+ Set `seed` to reproduce a BrainPy-State random realization. For `fixed_indegree`, set `allow_multapses=True` to match NEST's default and use `comm="sparse"` for large event fan-in. Open `references/nest-compatible/network-building.md` for the remaining rule constructors.
17
+
18
+ ## Static synapses
19
+
20
+ Use these constructors when edge weights do not change through activity-dependent learning.
21
+
22
+ | Constructor | Use when |
23
+ |---|---|
24
+ | `bp.static_synapse(*args, **kwargs)` | Use the default fixed-weight, fixed-delay synapse spec. |
25
+ | `bp.static_synapse_hom_w(*args, **kwargs)` | Use one homogeneous weight shared across all realized connections. |
26
+ | `bp.bernoulli_synapse(*args, **kwargs)` | Use fixed structural edges with stochastic Bernoulli transmission. |
27
+ | `bp.cont_delay_synapse(*args, **kwargs)` | Use a continuous sub-timestep delay. |
28
+
29
+ Pass `synapse=None` to `Simulator.connect()` for the ordinary static event path; instantiate a static spec only when its specialized behavior is required.
30
+
31
+ ## Gap junctions and special connections
32
+
33
+ Use these constructors for electrical, diffusion, rate, or astrocyte slow-inward-current coupling rather than ordinary static spike transmission.
34
+
35
+ | Constructor | Use when |
36
+ |---|---|
37
+ | `bp.gap_junction(*args, **kwargs)` | Use electrical synaptic coupling with a compatible gap-junction neuron. |
38
+ | `bp.diffusion_connection(*args, **kwargs)` | Use the NEST-compatible diffusion connection. |
39
+ | `bp.rate_connection_instantaneous(*args, **kwargs)` | Use rate coupling without a connection delay. |
40
+ | `bp.rate_connection_delayed(*args, **kwargs)` | Use delayed rate coupling. |
41
+ | `bp.sic_connection(*args, **kwargs)` | Use astrocyte-to-neuron slow inward current coupling. |
42
+
43
+ ## Short-term plasticity
44
+
45
+ Use these constructors for transient, reversible efficacy changes on the timescale of individual spikes.
46
+
47
+ | Constructor | Use when |
48
+ |---|---|
49
+ | `bp.tsodyks_synapse(*args, **kwargs)` | Use the Tsodyks-Uziel-Markram short-term-plasticity rule. |
50
+ | `bp.tsodyks_synapse_hom(*args, **kwargs)` | Use the homogeneous shared-parameter Tsodyks form. |
51
+ | `bp.tsodyks2_synapse(*args, **kwargs)` | Use the two-variable Tsodyks form. |
52
+ | `bp.quantal_stp_synapse(*args, **kwargs)` | Use the quantal/binomial short-term-plasticity form. |
53
+
54
+ ## Spike-timing-dependent plasticity
55
+
56
+ Use these constructors for long-term weight changes driven by pre-post spike timing; select the pairing, weight-dependence, triplet, hardware, or dopamine rule explicitly.
57
+
58
+ | Constructor | Use when |
59
+ |---|---|
60
+ | `bp.stdp_synapse(*args, **kwargs)` | Use pair-based STDP. |
61
+ | `bp.stdp_synapse_hom(*args, **kwargs)` | Use pair-based STDP with homogeneous shared parameters. |
62
+ | `bp.stdp_pl_synapse_hom(*args, **kwargs)` | Use power-law STDP. |
63
+ | `bp.stdp_facetshw_synapse_hom(*args, **kwargs)` | Use the FACETS/BrainScaleS hardware-emulating rule. |
64
+ | `bp.stdp_nn_pre_centered_synapse(*args, **kwargs)` | Use presynaptic-centered nearest-neighbour pairing. |
65
+ | `bp.stdp_nn_restr_synapse(*args, **kwargs)` | Use restricted symmetric nearest-neighbour pairing. |
66
+ | `bp.stdp_nn_symm_synapse(*args, **kwargs)` | Use symmetric nearest-neighbour pairing. |
67
+ | `bp.stdp_triplet_synapse(*args, **kwargs)` | Use triplet STDP. |
68
+ | `bp.stdp_dopamine_synapse(*args, **kwargs)` | Use dopamine-modulated STDP with a `volume_transmitter`. |
69
+
70
+ Open `references/nest-compatible/divergence-and-parity.md` before porting `tau_minus`, Clopath parameters, dopamine State, or a nearest-neighbour pairing rule.
71
+
72
+ ## Voltage-based and specialized learning
73
+
74
+ Use these constructors when the weight update depends on voltage trajectories, dendritic prediction, inhibitory timing, or the Hill-Tononi vesicle pool.
75
+
76
+ | Constructor | Use when |
77
+ |---|---|
78
+ | `bp.clopath_synapse(*args, **kwargs)` | Use voltage-based Clopath plasticity with a compatible `_clopath` neuron. |
79
+ | `bp.jonke_synapse(*args, **kwargs)` | Use exponential weight-dependence STDP. |
80
+ | `bp.urbanczik_synapse(*args, **kwargs)` | Use dendritic prediction-error plasticity with `pp_cond_exp_mc_urbanczik`. |
81
+ | `bp.vogels_sprekeler_synapse(*args, **kwargs)` | Use symmetric inhibitory plasticity. |
82
+ | `bp.ht_synapse(*args, **kwargs)` | Use Hill-Tononi vesicle-pool depression. |
83
+
84
+ ## Synapse specification
85
+
86
+ Use these `Simulator.connect()` arguments to attach a selected rule to realized edges.
87
+
88
+ | Argument | Use |
89
+ |---|---|
90
+ | `weight=<quantity>` | Use signed current such as `pA` for current-based event input; use voltage such as `mV` for the instantaneous jump of `iaf_psc_delta`. |
91
+ | `delay=<time quantity>` | Use for a homogeneous axonal delay. |
92
+ | `weight=[...] * unit` | Use for a multi-channel generator with one signed weight per channel. |
93
+ | `seed=<int>` | Use to reproduce the BrainPy-State random edge realization. |
94
+ | `allow_multapses=<bool>` | Use to permit or forbid repeated source-target edges under a random rule. |
95
+ | `comm="dense"` or `comm="sparse"` | Use to select the communication backend without changing the rule. |
96
+ | `synapse=<spec>` | Use to attach any constructor from the synapse families above. |
97
+
98
+ ```python
99
+ projection = sim.connect(
100
+ exc,
101
+ exc + inh,
102
+ rule=bp.fixed_indegree(80),
103
+ weight=0.1 * u.pA,
104
+ delay=1.5 * u.ms,
105
+ seed=1,
106
+ allow_multapses=True,
107
+ comm="sparse",
108
+ )
109
+ ```
110
+
111
+ **Invariant:** Do not copy one weight unit across neuron families. `iaf_psc_delta` consumes a voltage jump, while canonical alpha- and exponential-current events consume current.
112
+
113
+ ## Plastic connection workflow
114
+
115
+ Use `synapse=` when the edge needs State or behavior beyond static weight and delay.
116
+
117
+ ```python
118
+ plasticity = bp.tsodyks2_synapse(
119
+ weight=250.0 * u.pA,
120
+ U=0.67,
121
+ tau_rec=450.0 * u.ms,
122
+ tau_fac=0.0 * u.ms,
123
+ )
124
+ projection = sim.connect(spike_source, post, synapse=plasticity)
125
+ ```
126
+
127
+ **Invariant:** A BrainPy-State `spike_generator` can drive a plastic edge directly. Do not add a `parrot_neuron` solely because the NEST version required one.
128
+
129
+ ## Realized-connectivity inspection
130
+
131
+ Use these methods after construction to inspect or update the live edges selected by the rule.
132
+
133
+ | API | Use when |
134
+ |---|---|
135
+ | `sim.get_connections(source=None, target=None, synapse=None)` | Use to obtain an empty or populated lazy `SynapseCollection` filtered by source, target, or synapse name. |
136
+ | `connections.get(key)` | Use one key to read live `source`, `target`, `weight`, or `delay`, or a sequence to return several attributes as a dictionary; weights and delays retain units. |
137
+ | `connections.set(key, value)` | Use to write supported static `weight` or `delay` values; homogeneous, plastic, and other weight-evolving projections can reject the write. |
138
+
139
+ ```python
140
+ connections = sim.get_connections(source=exc, target=inh)
141
+ edge_data = connections.get(["source", "target", "weight", "delay"])
142
+
143
+ assert edge_data["source"].shape == edge_data["target"].shape
144
+ assert edge_data["weight"].shape == edge_data["source"].shape
145
+ ```
146
+
147
+ `SynapseCollection` re-reads live weights and delays, so a collection created before simulation reflects later plastic changes. Source and target indices are population-local, not global NEST node IDs.
148
+
149
+ ## Official sources
150
+
151
+ - https://brainx.chaobrain.com/brainpy-state/apis/nest-synapses.html
152
+ - https://brainx.chaobrain.com/brainpy-state/apis/nest-plasticity.html
153
+ - https://brainx.chaobrain.com/brainpy-state/nest-style/connectivity.html