brainx-skill 1.0.10 → 1.0.12

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 (62) hide show
  1. package/README.md +6 -0
  2. package/adapters/antigravity.js +8 -0
  3. package/installation/lib/installer.js +60 -20
  4. package/installation/lib/paths.js +41 -3
  5. package/installation/lib/prompts.js +13 -7
  6. package/manifest.json +2 -1
  7. package/package.json +3 -2
  8. package/skills/braincell/SKILL.md +1 -1
  9. package/skills/braincell/references/mixions-for-adaptation.md +26 -3
  10. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +113 -53
  11. package/skills/brainevent/references/synaptic-plasticity.md +74 -230
  12. package/skills/brainmass/SKILL.md +11 -6
  13. package/skills/brainmass/references/batch-transform-acceleration.md +44 -3
  14. package/skills/brainmass/references/modellibrary.md +11 -0
  15. package/skills/brainmass/references/simulator-input-monitor-api.md +98 -0
  16. package/skills/brainpy-state/SKILL.md +20 -6
  17. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +52 -1
  18. package/skills/brainpy-state/references/brainPy(legacy)/analysis.md +150 -0
  19. package/skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +373 -0
  20. package/skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +150 -0
  21. package/skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +175 -0
  22. package/skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +286 -0
  23. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +111 -0
  24. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +163 -0
  25. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +113 -0
  26. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +136 -0
  27. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +222 -0
  28. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +123 -0
  29. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +107 -0
  30. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +185 -0
  31. package/skills/brainpy-state/references/brainPy(legacy)/integrators.md +181 -0
  32. package/skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +102 -0
  33. package/skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +147 -0
  34. package/skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +159 -0
  35. package/skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +127 -0
  36. package/skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +167 -0
  37. package/skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +107 -0
  38. package/skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +186 -0
  39. package/skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +104 -0
  40. package/skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +89 -0
  41. package/skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +253 -0
  42. package/skills/brainpy-state/references/braintools/connectivity.md +206 -0
  43. package/skills/brainpy-state/references/braintools/input-current.md +199 -0
  44. package/skills/brainpy-state/references/component-selection.md +20 -5
  45. package/skills/brainpy-state/references/projection-patterns.md +2 -0
  46. package/skills/brainpy-state/references/scripts/sound_localization.py +240 -0
  47. package/skills/brainstate/SKILL.md +1 -1
  48. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +8 -0
  49. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +57 -7
  50. package/skills/brainstate/references/collective_model_operations.md +26 -27
  51. package/skills/braintrace/SKILL.md +161 -0
  52. package/skills/braintrace/references/Drtrl.md +179 -0
  53. package/skills/braintrace/references/ETP operators.md +161 -0
  54. package/skills/braintrace/references/algorithm selection.md +120 -0
  55. package/skills/braintrace/references/batching.md +150 -0
  56. package/skills/braintrace/references/compiler_internal.md +162 -0
  57. package/skills/braintrace/references/custom ETP primitives.md +200 -0
  58. package/skills/braintrace/references/custom algorithms.md +206 -0
  59. package/skills/braintrace/references/customizing_primitive_transforms.md +191 -0
  60. package/skills/braintrace/references/pp_pprop workflow.md +196 -0
  61. package/skills/braintrace/references/pre-built-braintrace-layer.md +149 -0
  62. package/skills/brainx-general-guard/SKILL.md +64 -21
@@ -0,0 +1,253 @@
1
+ # Training workflows
2
+
3
+ Use this reference after selecting a legacy BrainPy trainer. It covers the
4
+ canonical data and execution flow for offline reservoir fitting, online recurrent
5
+ fitting, backpropagation through time, and a custom gradient loop. Open
6
+ `trainer library.md` when the trainer family is still undecided.
7
+
8
+ ## Workflow selection
9
+
10
+ | Workflow | Use when | Essential order |
11
+ |---|---|---|
12
+ | Offline ridge | A readout can be solved from the complete state-target sequence. | Reset model -> warm up recurrent state -> fit `(X, Y)` -> predict held-out input. |
13
+ | Online RLS or FORCE | Readout parameters must update as time steps arrive. | Reset model -> warm up -> traverse paired training sequence while updating -> predict. |
14
+ | BPTT | Loss must differentiate through recurrent dynamics and trainable state. | Enter training mode -> construct model -> define loss and optimizer -> fit batches -> inspect metrics -> predict. |
15
+ | Custom backpropagation | The built-in trainer cannot express the required loss, gradient target, or update schedule. | Predict with `DSTrainer` -> differentiate selected train variables -> optimizer update inside one compiled step. |
16
+
17
+ ## Shared reservoir model and data contract
18
+
19
+ Online and offline reservoir trainers consume batch-major arrays. Keep time on
20
+ axis 1 and features on the final axis.
21
+
22
+ ```python
23
+ import brainpy as bp
24
+ import brainpy.math as bm
25
+
26
+
27
+ class NGRC(bp.DynamicalSystem):
28
+ def __init__(self, num_in, num_out):
29
+ super().__init__()
30
+ self.reservoir = bp.dyn.NVAR(
31
+ num_in,
32
+ delay=4,
33
+ order=2,
34
+ stride=5,
35
+ )
36
+ self.readout = bp.dnn.Dense(
37
+ self.reservoir.num_out,
38
+ num_out,
39
+ mode=bm.training_mode,
40
+ )
41
+
42
+ def update(self, x):
43
+ return self.readout(self.reservoir(x))
44
+
45
+
46
+ # Expected data shapes:
47
+ # warmup_x: (batch, warmup_time, features)
48
+ # train_x: (batch, train_time, features)
49
+ # train_y: (batch, train_time, outputs)
50
+ # test_x: (batch, test_time, features)
51
+ # test_y: (batch, test_time, outputs)
52
+ ```
53
+
54
+ Create the trainable readout in training mode. Keep `X` and `Y` aligned along
55
+ batch and time axes; a forecast-ahead task shifts the target time window without
56
+ changing those axes.
57
+
58
+ ## Offline ridge workflow
59
+
60
+ Use offline ridge when all reservoir states and targets can be collected before
61
+ solving the readout.
62
+
63
+ | API | Description |
64
+ |---|---|
65
+ | `RidgeTrainer(model, alpha=...)` | Use for the canonical closed-form ridge path; `alpha` controls Tikhonov regularization. |
66
+ | `trainer.predict(warmup_x)` | Use before fitting to advance delayed or recurrent state without changing fitted parameters. |
67
+ | `trainer.fit([train_x, train_y])` | Use to solve the readout from the complete paired sequence. |
68
+ | `trainer.predict(test_x)` | Use after fitting for held-out prediction. |
69
+
70
+ ```python
71
+ with bm.environment(bm.batching_mode):
72
+ offline_model = NGRC(num_in=3, num_out=3)
73
+
74
+ offline_model.reset(1)
75
+ offline = bp.RidgeTrainer(offline_model, alpha=1e-6)
76
+
77
+ _ = offline.predict(warmup_x)
78
+ _ = offline.fit([train_x, train_y])
79
+ offline_predictions = offline.predict(test_x)
80
+
81
+ assert offline_predictions.shape == test_y.shape
82
+ ```
83
+
84
+ Do not reset between warm-up and `fit()`: the warm-up exists to establish the
85
+ state from which the training sequence should begin. Reset explicitly before a
86
+ scientifically independent trial.
87
+
88
+ ## Online recurrent workflow
89
+
90
+ Use online fitting when the readout should update while the training sequence is
91
+ processed.
92
+
93
+ | API | Description |
94
+ |---|---|
95
+ | `OnlineTrainer(model, fit_method=bp.algorithms.RLS(), dt=...)` | Use for recursive least squares with explicit algorithm state and simulation step. |
96
+ | `trainer.predict(warmup_x)` | Use to establish recurrent history before learning. |
97
+ | `trainer.fit([train_x, train_y])` | Use to update parameters incrementally across paired time steps. |
98
+ | `trainer.predict(test_x)` | Use to evaluate the fitted recurrent model without further fitting. |
99
+
100
+ ```python
101
+ with bm.environment(bm.batching_mode):
102
+ online_model = NGRC(num_in=3, num_out=3)
103
+
104
+ online_model.reset(1)
105
+ online = bp.OnlineTrainer(
106
+ online_model,
107
+ fit_method=bp.algorithms.RLS(),
108
+ dt=0.01,
109
+ )
110
+
111
+ _ = online.predict(warmup_x)
112
+ _ = online.fit([train_x, train_y])
113
+ online_predictions = online.predict(test_x)
114
+
115
+ assert online_predictions.shape == test_y.shape
116
+ ```
117
+
118
+ Use `ForceTrainer` when the experiment specifically requires FORCE learning.
119
+ Keep the same warm-up, paired-fit, and held-out-prediction lifecycle.
120
+
121
+ ## BPTT workflow
122
+
123
+ Use `BPTT` when gradients must pass through the recurrent trajectory rather than
124
+ fit only a readout.
125
+
126
+ | API | Description |
127
+ |---|---|
128
+ | `bm.training_environment()` | Use while constructing the model so trainable layers and states receive training semantics. |
129
+ | `model.train_vars().unique()` | Use when the loss or optimizer needs the unique trainable-variable collection. |
130
+ | `BPTT(model, loss_fun=..., optimizer=...)` | Use to bind temporal simulation, differentiation, loss, and parameter updates. |
131
+ | `trainer.fit(train_data, num_epoch=...)` | Use with a callable or iterable yielding `(inputs, targets)` batches. |
132
+ | `trainer.get_hist_metric(phase='fit', metric='loss')` | Use to verify convergence after fitting. |
133
+
134
+ ```python
135
+ import brainpy as bp
136
+ import brainpy.math as bm
137
+
138
+
139
+ dt = 0.04
140
+ num_step = int(1.0 / dt)
141
+ num_batch = 128
142
+
143
+
144
+ @bm.jit
145
+ def make_batch(mean=0.025, scale=0.01):
146
+ sample = bm.random.normal(size=(num_batch, 1, 1))
147
+ bias = mean * 2.0 * (sample - 0.5)
148
+ noise = bm.random.normal(size=(num_batch, num_step, 1))
149
+ inputs = bias + scale / dt**0.5 * noise
150
+ targets = bm.cumsum(inputs, axis=1)
151
+ return inputs, targets
152
+
153
+
154
+ def train_data():
155
+ for _ in range(100):
156
+ yield make_batch()
157
+
158
+
159
+ class RNN(bp.DynamicalSystem):
160
+ def __init__(self, num_in, num_hidden):
161
+ super().__init__()
162
+ self.recurrent = bp.dyn.RNNCell(
163
+ num_in,
164
+ num_hidden,
165
+ train_state=True,
166
+ )
167
+ self.readout = bp.dnn.Dense(num_hidden, 1)
168
+
169
+ def update(self, x):
170
+ return self.readout(self.recurrent(x))
171
+
172
+
173
+ with bm.training_environment():
174
+ model = RNN(num_in=1, num_hidden=100)
175
+
176
+
177
+ def loss_fun(predictions, targets):
178
+ return bp.losses.mean_squared_error(predictions, targets)
179
+
180
+
181
+ schedule = bp.optim.ExponentialDecay(
182
+ lr=0.025,
183
+ decay_steps=1,
184
+ decay_rate=0.99975,
185
+ )
186
+ optimizer = bp.optim.Adam(lr=schedule, eps=1e-1)
187
+ trainer = bp.BPTT(model, loss_fun=loss_fun, optimizer=optimizer)
188
+
189
+ trainer.fit(train_data, num_epoch=30)
190
+ loss_history = trainer.get_hist_metric(phase='fit', metric='loss')
191
+
192
+ test_x, test_y = make_batch()
193
+ model.reset(num_batch)
194
+ predictions = trainer.predict(test_x)
195
+ assert predictions.shape == test_y.shape
196
+ assert loss_history is not None
197
+ ```
198
+
199
+ For a spiking model, keep the same BPTT lifecycle. Encode input as a batched time
200
+ series, pass required spike variables through `monitors`, and set
201
+ `loss_has_aux=True` when the loss returns metrics such as accuracy. Add spike
202
+ count penalties only when they express an intended training objective.
203
+
204
+ ## Custom backpropagation workflow
205
+
206
+ Use a custom loop only when `BPTT` cannot express the required gradient boundary
207
+ or update schedule.
208
+
209
+ | API | Description |
210
+ |---|---|
211
+ | `DSTrainer(model, progress_bar=False, numpy_mon_after_run=False)` | Use to obtain the model's temporal predictions inside a custom loss. |
212
+ | `bm.grad(loss_fun, grad_vars=model.train_vars().unique(), has_aux=..., return_value=True)` | Use to differentiate exactly the selected legacy BrainPy train variables and return loss or auxiliary metrics. |
213
+ | `bp.optim.Optimizer(..., train_vars=...)` | Use to bind the same variable collection to the update rule. |
214
+ | `@bm.jit` | Use around the complete gradient-and-update step, not around fragmented scalar operations. |
215
+
216
+ Reset the model inside the loss when each batch represents an independent
217
+ trajectory. Preserve state when batches are consecutive segments of one
218
+ trajectory. This choice changes the modeled history and must be explicit.
219
+
220
+ ## Common failures
221
+
222
+ - Do not construct a trainable readout outside the legacy training or batching
223
+ environment required by the model.
224
+ - Do not transpose trainer data to time-major form unless the configured runner
225
+ explicitly requires it; the canonical online and offline contract is
226
+ `(batch, time, feature)`.
227
+ - Do not skip warm-up for delayed or recurrent reservoirs.
228
+ - Do not reset between warm-up and fitting unless the fit sequence is intended
229
+ to start from a fresh state.
230
+ - Do not pass independent `X` and `Y` arguments to online or offline `fit()`;
231
+ pass one two-item list or tuple.
232
+ - Do not optimize every mutable variable by default. Select the unique trainable
233
+ variables and verify that state reset and parameter update affect the intended
234
+ objects.
235
+ - Do not replace these legacy training APIs with similarly named APIs from a
236
+ different BrainPy implementation.
237
+
238
+ ## Routing
239
+
240
+ - Open `trainer library.md` for the complete trainer-family selection table and
241
+ constructor contracts.
242
+ - Open `loss library.md` for built-in loss selection.
243
+ - Open `optimizers.md` for optimizer and learning-rate-schedule selection.
244
+ - Open `surrogate gradients.md` when a custom hard-threshold spiking model needs
245
+ an explicit surrogate derivative.
246
+ - Open `../infrastructure/object oriented transformations and control flows.md` when a custom loop
247
+ needs transformed scans, loops, or object-aware gradients.
248
+
249
+ ## Sources
250
+
251
+ - Training a Brain Dynamics Model: https://brainpy.readthedocs.io/quickstart/training.html
252
+ - Training with Online Algorithms: https://brainpy.readthedocs.io/tutorial_training/online_training.html
253
+ - Training with Back-propagation Algorithms: https://brainpy.readthedocs.io/tutorial_training/bp_training.html
@@ -0,0 +1,206 @@
1
+ # Braintools connectivity
2
+
3
+ Use this reference to choose and construct point-neuron or
4
+ multi-compartment connection patterns. It covers which pairs exist, their
5
+ indices, optional weights and delays, spatial structure, topology, and
6
+ compartment targeting. Use `braintools.init.DistanceModulated` only when an
7
+ existing connection's weight should be scaled by distance.
8
+
9
+ ## Choose a connectivity family
10
+
11
+ | Family | Use when | Representative choice |
12
+ |---|---|---|
13
+ | Basic point-neuron | Connection probability or deterministic pairing is enough | `Random`, `AllToAll`, or `OneToOne` |
14
+ | Spatial point-neuron | Positions or spatial neighborhoods determine connection probability | `DistanceDependent`, `Gaussian`, `Ring`, or `Grid2d` |
15
+ | Topological | Degree, clustering, modularity, hierarchy, or core/periphery structure matters | `SmallWorld`, `ScaleFree`, `ModularRandom`, or `HierarchicalRandom` |
16
+ | Biological E/I | Presynaptic sign must follow Dale's principle | `ExcitatoryInhibitory` |
17
+ | Kernel based | Receptive-field geometry should follow an image-like kernel | `GaussianKernel`, `GaborKernel`, or `DoGKernel` |
18
+ | Multi-compartment | Synapses must target soma, axon, or dendritic compartments | `CompartmentSpecific` or an anatomical targeting subclass |
19
+
20
+ ## Construction and results
21
+
22
+ Every connectivity object is a reusable pattern. Call it with population sizes
23
+ and any required positions or morphology metadata to obtain a
24
+ `ConnectionResult`.
25
+
26
+ | API | Description |
27
+ |---|---|
28
+ | `Connectivity(pre_size=None, post_size=None, seed=None)` | Subclass for a new general pattern. Implement `generate(...)`; use `weight_scale(factor)` or `delay_scale(factor)` to wrap a pattern. |
29
+ | `PointConnectivity` | Subclass for a new single-compartment pattern. |
30
+ | `MultiCompartmentConnectivity` | Subclass for a new morphology-aware pattern. |
31
+ | `ScaledConnectivity` | Returned when weights or delays are scaled. |
32
+ | `CompositeConnectivity` | Use when combining several connectivity patterns. |
33
+ | `ConnectionResult(pre_indices, post_indices, pre_size, post_size, ..., weights=None, delays=None, model_type='point', metadata=None)` | Inspect the generated edge list and optional annotations. `shape` is `(pre_size, post_size)` and `n_connections` is the number of edges. |
34
+ | `ConnectionResult.weight2dense()` / `weight2csr()` | Convert weights to a dense or CSR connectivity matrix. |
35
+ | `ConnectionResult.delay2matrix()` / `delay2csr()` | Convert delays to a dense or CSR connectivity matrix. |
36
+ | `ConnectionResult.get_distances()` | Compute distances for connected pairs when positions are available. |
37
+
38
+ ```python
39
+ import brainunit as u
40
+ from braintools.conn import ExcitatoryInhibitory
41
+
42
+ pattern = ExcitatoryInhibitory(
43
+ exc_ratio=0.8,
44
+ exc_prob=0.1,
45
+ inh_prob=0.2,
46
+ exc_weight=1.0 * u.nS,
47
+ inh_weight=-0.8 * u.nS,
48
+ )
49
+ result = pattern(pre_size=1000, post_size=1000)
50
+
51
+ assert result.shape == (1000, 1000)
52
+ assert result.pre_indices.shape == result.post_indices.shape
53
+ assert result.weights.shape[0] == result.n_connections
54
+ ```
55
+
56
+ **Invariant:** a `ConnectionResult` edge is identified by matching entries in
57
+ `pre_indices` and `post_indices`. Keep any weights and delays aligned with that
58
+ edge order when converting or filtering.
59
+
60
+ ## Basic and spatial point-neuron patterns
61
+
62
+ | API | Description |
63
+ |---|---|
64
+ | `Random(prob, allow_self_connections=False, weight=None, delay=None, **kwargs)` | Use for independent fixed-probability edges. Supply initializer objects or values for optional weights and delays. |
65
+ | `FixedProb(...)` | Use only as the alias for `Random`. |
66
+ | `AllToAll(...)` | Connect every allowed presynaptic/postsynaptic pair. |
67
+ | `OneToOne(...)` | Connect neuron `i` to neuron `i`; use only when the population indexing is aligned. |
68
+ | `DistanceDependent(distance_profile, weight=None, delay=None, allow_self_connections=False, **kwargs)` | Use when a `braintools.init.DistanceProfile` should determine connection probability from positions or precomputed distances. |
69
+ | `Gaussian(...)` | Use for Gaussian distance-dependent connection probability. |
70
+ | `Exponential(...)` | Use for exponentially decaying connection probability. |
71
+ | `Ring(...)` | Use for neurons arranged on a circular topology. |
72
+ | `Grid2d(connectivity='von_neumann', weight=None, delay=None, periodic=False, **kwargs)` | Use for immediate four-neighbor (`'von_neumann'`) or eight-neighbor (`'moore'`) connections on matching two-dimensional pre/post grids. Set `periodic=True` only for wraparound boundaries. |
73
+ | `RadialPatches(...)` | Use for several localized spatial connection patches. |
74
+ | `ClusteredRandom(...)` | Use for random connectivity enhanced within spatial clusters. |
75
+
76
+ ```python
77
+ import brainunit as u
78
+ import numpy as np
79
+ from braintools.conn import DistanceDependent
80
+ from braintools.init import GaussianProfile, LogNormal
81
+
82
+ positions = np.random.default_rng(0).uniform(0, 1000, (500, 2)) * u.um
83
+ pattern = DistanceDependent(
84
+ GaussianProfile(sigma=100 * u.um, max_distance=300 * u.um),
85
+ weight=LogNormal(mean=1.0 * u.nS, std=0.5 * u.nS),
86
+ )
87
+ result = pattern(500, 500, positions, positions)
88
+ ```
89
+
90
+ `DistanceDependent` consumes the profile's connection probability and samples
91
+ which pairs exist. In contrast, `braintools.init.DistanceModulated` multiplies
92
+ every supplied base weight by a profile value and never removes an edge.
93
+
94
+ ## Export a `ConnectionResult` to BrainEvent CSR
95
+
96
+ Choose topology with BrainTools before choosing BrainEvent storage. Convert the
97
+ result's coordinate edge list to CSR when binary presynaptic events should drive
98
+ event-based communication.
99
+
100
+ | API | Description |
101
+ |---|---|
102
+ | `brainevent.coo2csr(row_ids, col_ids, *, shape)` | Convert `pre_indices` and `post_indices` to row-compressed structure; it returns `(indptr, indices, order)`, where `order` is the required edge-value permutation. |
103
+ | `brainevent.CSR((data, indices, indptr), shape=...)` | Store the reordered weights with presynaptic rows and postsynaptic columns for `BinaryArray @ CSR`. |
104
+ | `brainevent.BinaryArray(spikes) @ connectivity` | Communicate active presynaptic events and return one accumulated value per postsynaptic index. |
105
+
106
+ ```python
107
+ import brainevent
108
+ import brainunit as u
109
+ from braintools.conn import Grid2d
110
+ from braintools.init import Constant
111
+
112
+ pattern = Grid2d(
113
+ connectivity="von_neumann",
114
+ weight=Constant(1.0 * u.nS),
115
+ periodic=False,
116
+ )
117
+ result = pattern(pre_size=(10, 10), post_size=(10, 10))
118
+
119
+ indptr, indices, order = brainevent.coo2csr(
120
+ result.pre_indices,
121
+ result.post_indices,
122
+ shape=result.shape,
123
+ )
124
+ connectivity = brainevent.CSR(
125
+ (result.weights[order], indices, indptr),
126
+ shape=result.shape,
127
+ )
128
+ postsynaptic_input = brainevent.BinaryArray(
129
+ u.math.zeros(result.shape[0], dtype=bool)
130
+ ) @ connectivity
131
+
132
+ assert postsynaptic_input.shape == (result.shape[1],)
133
+ ```
134
+
135
+ Keep `result.weights[order]`: `coo2csr()` sorts edges by row and returns the
136
+ matching value permutation separately. If the topology has no generated
137
+ weights, supply an intentional scalar or edge-aligned weight array before
138
+ constructing `CSR`.
139
+
140
+ Open `skills/brainevent/references/sparse-formats.md` when choosing among CSR,
141
+ CSC, dense, generated, or fixed-degree event representations after topology is
142
+ defined.
143
+
144
+ ## Topological and biological patterns
145
+
146
+ | API | Description |
147
+ |---|---|
148
+ | `SmallWorld(...)` | Use for Watts-Strogatz small-world structure. |
149
+ | `ScaleFree(...)` | Use for Barabasi-Albert preferential attachment. |
150
+ | `Regular(...)` | Use when each neuron should have the same degree. |
151
+ | `ModularRandom(...)` | Use for random within-module and between-module probabilities. |
152
+ | `ModularGeneral(...)` | Use when intra- and inter-module structure each need their own `Connectivity` object. |
153
+ | `HierarchicalRandom(...)` | Use for multilevel modules with asymmetric feedforward and feedback connectivity. |
154
+ | `CorePeripheryRandom(...)` | Use for a dense core and sparse periphery. |
155
+ | `ExcitatoryInhibitory(exc_ratio=0.8, exc_prob=0.1, inh_prob=0.2, exc_weight=None, inh_weight=None, exc_delay=None, inh_delay=None, **kwargs)` | Use for separate excitatory and inhibitory presynaptic populations whose outgoing signs follow Dale's principle. |
156
+
157
+ ## Kernel-based patterns
158
+
159
+ Use kernel patterns when source and target neurons occupy image-like spatial
160
+ grids and a local receptive-field operator defines edges.
161
+
162
+ | API | Description |
163
+ |---|---|
164
+ | `Conv2dKernel(...)` | Use a general convolutional kernel. |
165
+ | `GaussianKernel(...)` | Use a Gaussian receptive field. |
166
+ | `GaborKernel(...)` | Use an orientation-selective Gabor field. |
167
+ | `DoGKernel(...)` | Use a difference-of-Gaussians center-surround field. |
168
+ | `MexicanHat(...)` | Use a Laplacian-of-Gaussian field. |
169
+ | `SobelKernel(...)` | Use a Sobel orientation/edge kernel. |
170
+ | `LaplacianKernel(...)` | Use a Laplacian edge kernel. |
171
+ | `CustomKernel(...)` | Supply a user-defined kernel function. |
172
+
173
+ ## Multi-compartment patterns
174
+
175
+ Use `SOMA`, `BASAL_DENDRITE`, `APICAL_DENDRITE`, and `AXON` as the documented
176
+ compartment identifiers. Choose the narrowest pattern that expresses the
177
+ anatomical constraint.
178
+
179
+ | Family | API | Description |
180
+ |---|---|---|
181
+ | General | `CompartmentSpecific(...)` | Define source and target compartment rules directly. |
182
+ | General | `AllToAllCompartments(...)` | Connect all allowed compartment pairs. |
183
+ | General | `CustomCompartment(...)` | Supply a custom compartment-selection function. |
184
+ | Anatomical | `SomaToDendrite(...)` | Target dendrites from somatic sources. |
185
+ | Anatomical | `AxonToSoma(...)` | Target soma from axons. |
186
+ | Anatomical | `DendriteToSoma(...)` | Target soma from dendrites. |
187
+ | Anatomical | `AxonToDendrite(target_dendrites=None, **kwargs)` | Target selected dendritic compartments from axons. |
188
+ | Anatomical | `DendriteToDendrite(...)` | Connect dendritic compartments. |
189
+ | Morphology | `ProximalTargeting(...)` | Prefer proximal dendritic compartments. |
190
+ | Morphology | `DistalTargeting(...)` | Prefer distal dendritic compartments. |
191
+ | Morphology | `BranchSpecific(...)` | Restrict targets to specified branches. |
192
+ | Morphology | `MorphologyDistance(...)` | Use morphology-aware distances. |
193
+ | Dendritic | `DendriticTree(...)` | Configure separate basal/apical probabilities. |
194
+ | Dendritic | `BasalDendriteTargeting(...)` | Restrict targets to basal dendrites. |
195
+ | Dendritic | `ApicalDendriteTargeting(...)` | Restrict targets to apical dendrites. |
196
+ | Dendritic | `DendriticIntegration(...)` | Express dendritic integration patterns. |
197
+ | Axonal | `AxonalProjection(...)` | Build topographic axonal projections. |
198
+ | Axonal | `AxonalBranching(...)` | Build branching axonal patterns. |
199
+ | Axonal | `AxonalArborization(...)` | Build axonal arborization patterns. |
200
+ | Axonal | `TopographicProjection(...)` | Preserve source/target topography. |
201
+ | Synaptic | `SynapticPlacement(...)` | Apply synapse-placement rules. |
202
+ | Synaptic | `SynapticClustering(...)` | Cluster synapses on target morphology. |
203
+
204
+ ## Official source
205
+
206
+ - `https://brainx.chaobrain.com/braintools/apis/conn.html`
@@ -0,0 +1,199 @@
1
+ # Braintools input currents
2
+
3
+ Use this reference to generate unit-aware stimulation currents, waveforms,
4
+ pulses, and stochastic processes. Prefer the composable class API when a
5
+ protocol combines, transforms, repeats, or sequences several signals; use the
6
+ functional API for one direct array.
7
+
8
+ ## Choose an interface
9
+
10
+ | Interface | Use when | Result |
11
+ |---|---|---|
12
+ | Composable classes | The protocol needs algebra, clipping, smoothing, time shifts, repetition, overlays, or concatenation | Returns an `Input` object; call it to generate the array. |
13
+ | Functional helpers | One signal can be generated in a single call | Returns the generated array immediately. |
14
+
15
+ Names ending in `Input` or `_input` are deprecated aliases. Use the class and
16
+ function names documented below.
17
+
18
+ ## Time-step and composition model
19
+
20
+ An `Input` stores a duration and reads its time step from
21
+ `brainstate.environ`. Calling it generates a cached array; pass
22
+ `recompute=True` when the stochastic or environmental inputs must be evaluated
23
+ again.
24
+
25
+ | API | Description |
26
+ |---|---|
27
+ | `Input(duration)` | Base class for composable currents. It exposes `duration`, `dt`, `n_steps`, and `shape`. |
28
+ | `input_obj(recompute=False)` | Generate and return the current array. |
29
+ | `input_obj.scale(factor)` | Multiply all values by a factor. |
30
+ | `input_obj.shift(time_shift)` | Delay or advance the signal in time. |
31
+ | `input_obj.clip(min_val, max_val)` | Bound the signal values. |
32
+ | `input_obj.smooth(tau)` | Apply exponential smoothing. |
33
+ | `input_obj.repeat(n_times)` | Repeat the pattern. |
34
+ | `input_obj.apply(func)` | Apply a custom transformation to the generated values. |
35
+ | `a + b`, `a - b`, `a * b`, `a / b`, `-a` | Combine compatible signals pointwise. |
36
+ | `a & b` | Concatenate signals sequentially in time. |
37
+ | `a \| b` | Overlay signals by taking their pointwise maximum. |
38
+
39
+ ```python
40
+ import brainstate
41
+ import brainunit as u
42
+ from braintools.input import Constant, Ramp, Sinusoidal
43
+
44
+ with brainstate.environ.context(dt=0.1 * u.ms):
45
+ baseline = Constant([(0.2 * u.nA, 500 * u.ms)])
46
+ ramp = Ramp(0 * u.nA, 1 * u.nA, 500 * u.ms)
47
+ oscillation = Sinusoidal(
48
+ amplitude=0.5 * u.nA,
49
+ frequency=10 * u.Hz,
50
+ duration=500 * u.ms,
51
+ )
52
+ protocol = (baseline + ramp + 0.5 * oscillation).clip(
53
+ 0 * u.nA,
54
+ 2 * u.nA,
55
+ )
56
+ current = protocol()
57
+ assert current.shape[0] == protocol.n_steps
58
+ ```
59
+
60
+ **Invariant:** set or scope `brainstate.environ.dt` before constructing and
61
+ generating the protocol. A different `dt` changes the number of samples.
62
+
63
+ ## Feed a protocol into a BrainPy-State rollout
64
+
65
+ A generated protocol is time-major data: construct it under the rollout `dt`,
66
+ then give it to `for_loop` so one current sample reaches each model step.
67
+
68
+ | API | Description |
69
+ |---|---|
70
+ | `Constant([(value, duration), ...])` | Use for a baseline-pulse-baseline protocol; calling it under the active `dt` returns one unit-aware sample per step. |
71
+ | `brainstate.transform.for_loop(step, times, current)` | Slice `times` and `current` together along their leading axes and stack the step outputs. |
72
+
73
+ ```python
74
+ import brainpy
75
+ import brainstate
76
+ import braintools
77
+ import brainunit as u
78
+ from braintools.input import Constant
79
+
80
+ with brainstate.environ.context(dt=0.1 * u.ms):
81
+ neuron = brainpy.state.LIFRef(
82
+ 3,
83
+ R=100.0 * u.Mohm,
84
+ tau=20.0 * u.ms,
85
+ V_rest=-65.0 * u.mV,
86
+ V_th=-50.0 * u.mV,
87
+ V_reset=-60.0 * u.mV,
88
+ tau_ref=2.0 * u.ms,
89
+ V_initializer=braintools.init.Constant(-65.0 * u.mV),
90
+ )
91
+ brainstate.nn.init_all_states(neuron)
92
+ protocol = Constant([
93
+ (0.0 * u.nA, 15.0 * u.ms),
94
+ (0.65 * u.nA, 4.0 * u.ms),
95
+ (0.0 * u.nA, 81.0 * u.ms),
96
+ ])
97
+ spark = protocol()
98
+ times = u.math.arange(
99
+ 0.0 * u.ms,
100
+ protocol.duration,
101
+ brainstate.environ.get_dt(),
102
+ )
103
+ edge_mask = u.math.asarray([True, False, False])
104
+
105
+ def step(t, spark_current):
106
+ with brainstate.environ.context(t=t):
107
+ return neuron(0.13 * u.nA + edge_mask * spark_current)
108
+
109
+ spikes = brainstate.transform.for_loop(step, times, spark)
110
+
111
+ assert spikes.shape == (1000, 3)
112
+ ```
113
+
114
+ Do not reconstruct the same sections with comparisons against `t` inside
115
+ `step`. For a mapped parameter sweep that shares this protocol, keep the
116
+ per-step current sample unmapped (`in_axes=None`) while mapping the independent
117
+ condition parameters and dynamical State. Open
118
+ `skills/brainstate/references/brainstate/transformation-vmap-expansion.md` for
119
+ the mapped-State contract.
120
+
121
+ ## Basic currents
122
+
123
+ | Composable API | Functional API | Use |
124
+ |---|---|---|
125
+ | `Section(values, durations)` | `section(values, durations, return_length=False)` | Build consecutive constant sections from parallel value and duration sequences. |
126
+ | `Constant(I_and_duration)` | `constant(I_and_duration)` | Build piecewise-constant sections from `(value, duration)` pairs. |
127
+ | `Step(amplitudes, step_times, duration=None)` | `step(amplitudes, step_times, duration=None)` | Change among discrete levels at specified times. |
128
+ | `Ramp(c_start, c_end, duration, t_start=None, t_end=None)` | `ramp(c_start, c_end, duration, t_start=None, t_end=None)` | Interpolate linearly, optionally only within a subinterval. |
129
+
130
+ `Constant` takes a sequence of pairs:
131
+
132
+ ```python
133
+ from braintools.input import Constant
134
+
135
+ protocol = Constant([
136
+ (0.0 * u.nA, 100 * u.ms),
137
+ (1.0 * u.nA, 200 * u.ms),
138
+ (0.0 * u.nA, 100 * u.ms),
139
+ ])
140
+ ```
141
+
142
+ Use `Section(values=[...], durations=[...])` when separate arrays are more
143
+ convenient.
144
+
145
+ ## Pulse generators
146
+
147
+ | Composable API | Functional API | Use |
148
+ |---|---|---|
149
+ | `Spike(sp_times, duration, sp_lens=..., sp_sizes=...)` | `spike(sp_times, sp_lens, sp_sizes, duration)` | Place short current spikes at explicit times. |
150
+ | `GaussianPulse(amplitude, center, sigma, duration)` | `gaussian_pulse(amplitude, center, sigma, duration, ...)` | Generate a Gaussian-shaped pulse. |
151
+ | `ExponentialDecay(amplitude, tau, duration, ...)` | `exponential_decay(amplitude, tau, duration, ...)` | Generate a one-sided exponential decay. |
152
+ | `DoubleExponential(amplitude, tau_rise, tau_decay, ...)` | `double_exponential(amplitude, tau_rise, tau_decay, ...)` | Generate a rise-and-decay synaptic-current shape. |
153
+ | `Burst(...)` | `burst(...)` | Generate repeated pulses within one or more bursts. |
154
+
155
+ ## Waveforms
156
+
157
+ | Composable API | Functional API | Use |
158
+ |---|---|---|
159
+ | `Sinusoidal(amplitude, frequency, duration, ...)` | `sinusoidal(amplitude, frequency, duration, ...)` | Generate a fixed-frequency sine wave. |
160
+ | `Square(amplitude, frequency, duration, ...)` | `square(amplitude, frequency, duration, ...)` | Generate a square wave; configure its duty cycle deliberately. |
161
+ | `Triangular(amplitude, frequency, duration, ...)` | `triangular(amplitude, frequency, duration, ...)` | Generate a triangular periodic wave. |
162
+ | `Sawtooth(amplitude, frequency, duration, ...)` | `sawtooth(amplitude, frequency, duration, ...)` | Generate a sawtooth periodic wave. |
163
+ | `Chirp(amplitude, f_start, f_end, duration, ...)` | `chirp(amplitude, f_start, f_end, duration, ...)` | Sweep frequency over time. |
164
+ | `NoisySinusoidal(amplitude, frequency, ..., noise_amplitude=...)` | `noisy_sinusoidal(amplitude, frequency, ..., noise_amplitude=...)` | Add stochastic noise to a sinusoid. |
165
+
166
+ ## Stochastic processes
167
+
168
+ | Composable API | Functional API | Use |
169
+ |---|---|---|
170
+ | `WienerProcess(duration, n=1, t_start=None, t_end=None, sigma=1.0, seed=None)` | `wiener_process(duration, sigma=1.0, n=1, ...)` | Model Brownian fluctuations with independent Gaussian increments. |
171
+ | `OUProcess(mean, sigma, tau, duration, n=1, t_start=None, t_end=None, seed=None)` | `ou_process(mean, sigma, tau, duration, n=1, ...)` | Model mean-reverting fluctuations around `mean`. |
172
+ | `Poisson(rate, duration, n=1, t_start=None, t_end=None, amplitude=1.0, seed=None)` | `poisson(rate, duration, amplitude=1.0, n=1, ...)` | Generate independent Poisson spike-current trains. |
173
+
174
+ Use `seed=` for reproducibility and `n=` for multiple independent processes.
175
+ For Poisson input, ensure `rate * dt` is a valid per-bin spike probability.
176
+ Call with `recompute=True` only when a new stochastic realization is intended.
177
+
178
+ ## Composition wrappers
179
+
180
+ These classes are normally created through operators or methods rather than
181
+ instantiated directly.
182
+
183
+ | API | Description |
184
+ |---|---|
185
+ | `Composite(input1, input2, operator)` | Pointwise combination of two inputs. |
186
+ | `ConstantValue(value, duration)` | Promote a scalar to a duration-matched input. |
187
+ | `Sequential(*inputs)` | Time concatenation corresponding to `&`. |
188
+ | `TimeShifted(input_obj, time_shift)` | Result of `.shift()`. |
189
+ | `Clipped(input_obj, min_val=None, max_val=None)` | Result of `.clip()`. |
190
+ | `Smoothed(input_obj, tau)` | Result of `.smooth()`. |
191
+ | `Repeated(input_obj, n_times)` | Result of `.repeat()`. |
192
+ | `Transformed(input_obj, func)` | Result of `.apply()`. |
193
+
194
+ Pointwise operands must have compatible duration, shape, and units. Use `&`
195
+ when durations differ and should occur one after another.
196
+
197
+ ## Official source
198
+
199
+ - `https://brainx.chaobrain.com/braintools/apis/input.html`