brainx-skill 1.0.10 → 1.0.11

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 (53) 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 +14 -0
  9. package/skills/brainevent/SKILL.md +1 -0
  10. package/skills/brainmass/SKILL.md +1 -1
  11. package/skills/brainpy-state/SKILL.md +7 -1
  12. package/skills/brainpy-state/references/array-creation.md +2 -2
  13. package/skills/brainpy-state/references/brainPy(legacy)/analysis.md +150 -0
  14. package/skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +373 -0
  15. package/skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +150 -0
  16. package/skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +175 -0
  17. package/skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +286 -0
  18. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +111 -0
  19. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +163 -0
  20. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +113 -0
  21. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +136 -0
  22. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +222 -0
  23. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +123 -0
  24. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +107 -0
  25. package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +185 -0
  26. package/skills/brainpy-state/references/brainPy(legacy)/integrators.md +181 -0
  27. package/skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +102 -0
  28. package/skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +147 -0
  29. package/skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +159 -0
  30. package/skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +127 -0
  31. package/skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +167 -0
  32. package/skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +107 -0
  33. package/skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +186 -0
  34. package/skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +104 -0
  35. package/skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +89 -0
  36. package/skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +253 -0
  37. package/skills/brainstate/SKILL.md +14 -10
  38. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +1 -1
  39. package/skills/brainstate/references/braintools/optimizer.md +179 -0
  40. package/skills/braintrace/SKILL.md +161 -0
  41. package/skills/braintrace/references/Drtrl.md +179 -0
  42. package/skills/braintrace/references/ETP operators.md +161 -0
  43. package/skills/braintrace/references/algorithm selection.md +120 -0
  44. package/skills/braintrace/references/batching.md +150 -0
  45. package/skills/braintrace/references/compiler_internal.md +162 -0
  46. package/skills/braintrace/references/custom ETP primitives.md +200 -0
  47. package/skills/braintrace/references/custom algorithms.md +206 -0
  48. package/skills/braintrace/references/customizing_primitive_transforms.md +191 -0
  49. package/skills/braintrace/references/pp_pprop workflow.md +196 -0
  50. package/skills/braintrace/references/pre-built-braintrace-layer.md +149 -0
  51. package/skills/brainx-general-guard/SKILL.md +20 -2
  52. package/skills/brainx-install/SKILL.md +24 -21
  53. package/skills/brainstate/agents/openai.yaml +0 -4
@@ -0,0 +1,373 @@
1
+ # Legacy BrainPy workflow
2
+
3
+ ## Purpose and boundary
4
+
5
+ Use this workflow for legacy BrainPy 2.x simulation, training, analysis, and object-oriented transformation.
6
+
7
+ Use only legacy `brainpy` APIs. Route modern `brainpy.state` work elsewhere.
8
+
9
+ Legacy BrainPy is not fully compatible with BrainX: do not combine it with BrainUnit or BrainTrace; BrainState, BrainEvent, and Braintools are compatible with BrainPy legacy. For any cellular modeling, use BrainPy-State with BrainCell; never use legacy BrainPy ion dynamics or ion-channel dynamics.
10
+
11
+ ## Underlying principle of legacy BrainPy
12
+
13
+ `DynamicalSystem` represents an evolving neuron, synapse, population, or network. Its `update()` method advances the biological dynamics one step; nesting composes cellular, synaptic, circuit, and network scales.
14
+
15
+ `brainpy.math.Variable` stores time-varying neural state such as membrane potential, channel gates, conductance, synaptic current, spikes, firing rate, or adaptation.
16
+
17
+ `brainpy.connect` defines neural wiring; `brainpy.dyn` projections carry presynaptic activity through synaptic dynamics into postsynaptic input.
18
+
19
+ `DSRunner` represents an in-silico protocol: apply stimuli, advance the model, and record neural time series.
20
+
21
+ ### API structure
22
+
23
+ Choose the namespace that owns the operation:
24
+
25
+ | API | Use |
26
+ |---|---|
27
+ | `brainpy` module | Define core objects and expose legacy runners, trainers, visualization, and top-level APIs. |
28
+ | `brainpy.math` module | Create arrays and Variables; configure execution; apply object-aware transformations and control flow. |
29
+ | `brainpy.dnn` module | Build trainable neural-network and communication layers. |
30
+ | `brainpy.dyn` module | Select neuron, synapse, projection, reservoir, and recurrent dynamics. |
31
+ | `brainpy.integrators` module | Construct and configure ODE, SDE, FDE, and joint-equation integrators. |
32
+ | `brainpy.analysis` module | Analyze phase planes, bifurcations, fast-slow systems, and fixed or slow points. |
33
+ | `brainpy.connect` module | Construct and inspect neural connectivity. |
34
+ | `brainpy.encoding` module | Encode continuous or categorical data into neural activity and spike representations. |
35
+ | `brainpy.initialize` module | Initialize model state, parameters, and trainable weights. |
36
+ | `brainpy.inputs` module | Generate time-varying currents, stimuli, and spike inputs. |
37
+ | `brainpy.losses` module | Compute training objectives and regularization penalties. |
38
+ | `brainpy.measure` module | Measure neural activity and relationships from simulation outputs. |
39
+ | `brainpy.optim` module | Optimize trainable Variables and schedule learning rates. |
40
+ | `brainpy.running` module | Execute independent experiments and parameter sweeps. |
41
+ | `brainpy.mixin` module | Provide behavioral contracts shared by legacy dynamics and projections. |
42
+
43
+ ### 1. Simulate dynamics with `DSRunner`
44
+
45
+ `DSRunner` advances one legacy `DynamicalSystem` through a structural time loop while applying inputs and recording time-major monitor histories.
46
+
47
+ | API | Description |
48
+ |---|---|
49
+ | `bp.DSRunner(target, inputs=..., monitors=..., jit=..., dt=...)` | Use for the canonical simulation; it binds one `DynamicalSystem` to its input, monitor, timestep, and compilation policy. |
50
+ | `runner.run(duration=..., inputs=..., reset_state=...)` | Use to execute a duration or a time-indexed input; set `reset_state` explicitly when the run must be independent. |
51
+ | `runner.mon.ts` | Use after execution for the generated time axis. |
52
+ | `runner.mon[name]` | Use after execution for the time-major trajectory registered under `name`. |
53
+ | `bm.for_loop(step, operands)` | Use instead when a custom step function and its returned values express the rollout more directly than runner inputs and monitors. |
54
+
55
+ ```python
56
+ import brainpy as bp
57
+ import brainpy.math as bm
58
+
59
+
60
+ bm.set_dt(0.1)
61
+ neurons = bp.dyn.LifRef(
62
+ 10,
63
+ V_rest=-60.0,
64
+ V_reset=-60.0,
65
+ V_th=-50.0,
66
+ tau=20.0,
67
+ tau_ref=5.0,
68
+ V_initializer=bp.init.Constant(-60.0),
69
+ )
70
+
71
+ runner = bp.DSRunner(
72
+ target=neurons,
73
+ monitors=['V', 'spike'],
74
+ jit=True,
75
+ progress_bar=False,
76
+ )
77
+ stimulus = bm.ones(1000) * 20.0
78
+ runner.run(inputs=stimulus, reset_state=True)
79
+
80
+ assert runner.mon['V'].shape == (1000, 10)
81
+ assert runner.mon['spike'].shape == (1000, 10)
82
+ assert runner.mon.ts.shape == (1000,)
83
+ ```
84
+
85
+ Monitor only the Variables, names, and neuron indices required by the analysis; reset explicitly before an independent rollout.
86
+
87
+ Open `infrastructure/More about simulation.md` when configuring static, iterable, or functional inputs; indexed or callable monitors; repeated rollouts; prediction axes; or state reset. Open `infrastructure/Input generation.md` when constructing stimulus arrays.
88
+
89
+ ### 2. Fit a reservoir readout
90
+
91
+ `RidgeTrainer` keeps reservoir dynamics fixed and solves a trainable linear readout from the complete state-target sequence, so warm-up must precede fitting without an intervening reset.
92
+
93
+ | API | Description |
94
+ |---|---|
95
+ | `bm.environment(bm.batching_mode)` | Use while constructing the canonical reservoir model so its trainable readout receives batched execution semantics. |
96
+ | `bd.chaos.LorenzEq(duration, dt=...)` | Use for the official quickstart's Lorenz forecasting data; it requires the optional `brainpy_datasets` package and returns time-indexed `xs`, `ys`, and `zs`. |
97
+ | `bp.dyn.NVAR(...)` | Use for the source-backed nonlinear vector autoregression reservoir with delayed polynomial features. |
98
+ | `bp.RidgeTrainer(model, alpha=...)` | Use when the complete reservoir-state matrix can be collected before solving the readout; `alpha` controls ridge regularization. |
99
+ | `trainer.predict(warmup_x)` | Use before fitting to establish delayed reservoir state without updating the readout. |
100
+ | `trainer.fit([train_x, train_y])` | Use to solve the readout from batch-major, time-aligned input and target sequences. |
101
+ | `trainer.predict(test_x)` | Use after fitting for held-out prediction. |
102
+
103
+ ```python
104
+ import brainpy as bp
105
+ import brainpy.math as bm
106
+ import brainpy_datasets as bd
107
+
108
+
109
+ def get_subset(data, start, end):
110
+ values = bm.hstack([
111
+ data.xs[start:end],
112
+ data.ys[start:end],
113
+ data.zs[start:end],
114
+ ])
115
+ return values.reshape((1,) + values.shape)
116
+
117
+
118
+ class NGRC(bp.DynamicalSystem):
119
+ def __init__(self, num_in, num_out):
120
+ super().__init__()
121
+ self.reservoir = bp.dyn.NVAR(
122
+ num_in,
123
+ delay=4,
124
+ order=2,
125
+ stride=5,
126
+ )
127
+ self.readout = bp.dnn.Dense(
128
+ self.reservoir.num_out,
129
+ num_out,
130
+ mode=bm.training_mode,
131
+ )
132
+
133
+ def update(self, x):
134
+ return self.readout(self.reservoir(x))
135
+
136
+
137
+ dt = 0.01
138
+ data = bd.chaos.LorenzEq(100.0, dt=dt)
139
+ warmup_x = get_subset(data, 0, int(20.0 / dt))
140
+ train_x = get_subset(data, int(20.0 / dt), int(80.0 / dt))
141
+ train_y = get_subset(data, int(20.0 / dt) + 1, int(80.0 / dt) + 1)
142
+ test_x = get_subset(data, int(80.0 / dt), int(100.0 / dt) - 1)
143
+ test_y = get_subset(data, int(80.0 / dt) + 1, int(100.0 / dt))
144
+
145
+ with bm.environment(bm.batching_mode):
146
+ model = NGRC(num_in=3, num_out=3)
147
+
148
+ model.reset(1)
149
+ trainer = bp.RidgeTrainer(model, alpha=1e-6)
150
+ _ = trainer.predict(warmup_x)
151
+ _ = trainer.fit([train_x, train_y])
152
+ predictions = trainer.predict(test_x)
153
+ test_loss = bp.losses.mean_squared_error(test_y, predictions)
154
+
155
+ assert predictions.shape == test_y.shape
156
+ assert test_loss.ndim == 0
157
+ ```
158
+
159
+ Keep data batch-major as `(batch, time, feature)` and align shifted forecast targets to the input length. Do not reset between warm-up and fitting.
160
+
161
+ Open `training/trainingworkflows.md` when choosing offline ridge, online RLS or FORCE, BPTT, or a custom gradient loop. Open `training/trainer library.md` when selecting among `RidgeTrainer`, `OfflineTrainer`, `OnlineTrainer`, `ForceTrainer`, `BPTT`, and `BPFF`.
162
+
163
+ ### 3. Train recurrent dynamics through time
164
+
165
+ `BPTT` differentiates a temporal loss through recurrent dynamics, updates only trainable Variables, and preserves ordinary dynamical state as rollout state rather than optimizer parameters.
166
+
167
+ | API | Description |
168
+ |---|---|
169
+ | `bm.training_environment()` | Use while constructing the model so recurrent cells, readouts, and trainable state receive legacy training semantics. |
170
+ | `bp.BPTT(model, loss_fun=..., optimizer=...)` | Use when the loss must propagate through a recurrent or spiking trajectory; it binds rollout, differentiation, loss, and updates. |
171
+ | `trainer.fit(train_data, num_epoch=...)` | Use with an iterable or callable yielding `(inputs, targets)` batches. |
172
+ | `trainer.get_hist_metric(phase='fit', metric='loss')` | Use after fitting to inspect recorded training loss. |
173
+ | `model.reset(batch_size)` | Use before an independent evaluation trajectory so predictions do not inherit training state. |
174
+ | `trainer.predict(inputs)` | Use after fitting to execute the trained temporal model. |
175
+
176
+ ```python
177
+ import brainpy as bp
178
+ import brainpy.math as bm
179
+
180
+
181
+ dt = 0.04
182
+ num_step = int(1.0 / dt)
183
+ num_batch = 32
184
+
185
+
186
+ @bm.jit
187
+ def make_batch(mean=0.025, scale=0.01):
188
+ sample = bm.random.normal(size=(num_batch, 1, 1))
189
+ bias = mean * 2.0 * (sample - 0.5)
190
+ noise = bm.random.normal(size=(num_batch, num_step, 1))
191
+ inputs = bias + scale / dt**0.5 * noise
192
+ targets = bm.cumsum(inputs, axis=1)
193
+ return inputs, targets
194
+
195
+
196
+ def train_data():
197
+ for _ in range(10):
198
+ yield make_batch()
199
+
200
+
201
+ class RNN(bp.DynamicalSystem):
202
+ def __init__(self, num_in, num_hidden):
203
+ super().__init__()
204
+ self.recurrent = bp.dyn.RNNCell(
205
+ num_in,
206
+ num_hidden,
207
+ train_state=True,
208
+ )
209
+ self.readout = bp.dnn.Dense(num_hidden, 1)
210
+
211
+ def update(self, x):
212
+ return self.readout(self.recurrent(x))
213
+
214
+
215
+ with bm.training_environment():
216
+ model = RNN(num_in=1, num_hidden=100)
217
+
218
+
219
+ def loss_fun(predictions, targets):
220
+ return bp.losses.mean_squared_error(predictions, targets)
221
+
222
+
223
+ trainer = bp.BPTT(
224
+ model,
225
+ loss_fun=loss_fun,
226
+ optimizer=bp.optim.Adam(lr=1e-3),
227
+ )
228
+ trainer.fit(train_data, num_epoch=2)
229
+ loss_history = trainer.get_hist_metric(phase='fit', metric='loss')
230
+
231
+ test_x, test_y = make_batch()
232
+ model.reset(num_batch)
233
+ predictions = trainer.predict(test_x)
234
+
235
+ assert predictions.shape == test_y.shape
236
+ assert len(loss_history) > 0
237
+ ```
238
+
239
+ Reset recurrent state only at independent sequence boundaries; keep rollout Variables out of optimizer updates.
240
+
241
+ Open `training/trainingworkflows.md` for online, offline, BPTT, custom-gradient, and reset workflows. Open `training/loss library.md`, `training/optimizers.md`, or `training/surrogate gradients.md` after fixing output reduction and the gradient boundary.
242
+
243
+ ### 4. Analyze model dynamics
244
+
245
+ Legacy analyzers reuse a constructed model but require explicit state ranges, swept or fixed parameters, and resolution so the resulting dynamical structure answers the intended question.
246
+
247
+ | API | Description |
248
+ |---|---|
249
+ | `bm.enable_x64()` | Use before constructing a numerically sensitive analyzer so root finding and stability calculations run at higher precision. |
250
+ | `bp.analysis.Bifurcation1D(...)` | Use to continue fixed points of a one-variable model while one or more parameters vary. |
251
+ | `bp.analysis.PhasePlane2D(...)` | Use to compute nullclines, vector fields, fixed points, and trajectories for two state variables. |
252
+ | `bp.analysis.SlowPointFinder(...)` | Use when a high-dimensional model requires candidate-based fixed- or slow-point optimization and optional Jacobians. |
253
+
254
+ ```python
255
+ import brainpy as bp
256
+ import brainpy.math as bm
257
+
258
+
259
+ bm.enable_x64()
260
+ model = bp.dyn.ExpIF(1, delta_T=1.0)
261
+
262
+ bifurcation = bp.analysis.Bifurcation1D(
263
+ model=model,
264
+ target_vars={'V': [-70.0, -55.0]},
265
+ target_pars={'I': [0.0, 6.0]},
266
+ resolutions={'I': 0.01},
267
+ )
268
+ bifurcation.plot_bifurcation(show=True)
269
+ ```
270
+
271
+ Match Variable and parameter names exactly; validate ranges and resolution against simulation before interpreting missing structure.
272
+
273
+ Open `analysis.md` when choosing phase-plane, bifurcation, fast-slow, fixed-point, slow-point, or linearization analysis, or when configuring candidates and post-processing.
274
+
275
+ ### 5. Make mutable state visible to transformations
276
+
277
+ Legacy object-aware transformations separate discoverable `Variable` state from static Python structure, preserving mutation across JIT compilation, differentiation, vectorization, and control flow.
278
+
279
+ | API | Description |
280
+ |---|---|
281
+ | `bp.BrainPyObject` | Subclass when an object owns Variables or nested BrainPy objects that transformations must discover. |
282
+ | `bm.Variable(value)` | Store mutable dynamical state and update its array through `.value`. |
283
+ | `bm.TrainVar(value)` | Mark only optimizer-controlled state as trainable. |
284
+ | `bm.NodeList`, `bm.NodeDict` | Store nested BrainPy objects in traversal-aware containers. |
285
+ | `bm.VarList`, `bm.VarDict` | Store Variables in traversal-aware containers. |
286
+ | `bm.jit(...)`, `bm.cls_jit` | Compile functions or bound methods while preserving discovered Variable mutation. |
287
+ | `bm.grad(...)` | Differentiate with respect to explicit arguments or discovered trainable Variables. |
288
+ | `bm.for_loop(...)` | Compile a fixed-length loop and stack step outputs without a Python timestep loop. |
289
+
290
+ ```python
291
+ import brainpy as bp
292
+ import brainpy.math as bm
293
+
294
+
295
+ class Accumulator(bp.BrainPyObject):
296
+ def __init__(self):
297
+ super().__init__()
298
+ self.total = bm.Variable(bm.zeros(1))
299
+
300
+ @bm.cls_jit
301
+ def __call__(self, value):
302
+ self.total.value += value
303
+ return self.total.value
304
+
305
+
306
+ accumulator = Accumulator()
307
+ assert bm.allclose(accumulator(2.0), bm.array([2.0]))
308
+ assert bm.allclose(accumulator(3.0), bm.array([5.0]))
309
+ ```
310
+
311
+ Update discovered Variables through `.value`, indexed assignment, or augmented assignment; rebinding them or changing ordinary attributes after tracing is invisible to compiled code. Store nested objects and Variables on attributes or in `NodeList`, `NodeDict`, `VarList`, or `VarDict`.
312
+
313
+ Open `infrastructure/object oriented transformations and control flows.md` when choosing JIT, gradients, Jacobians, vectorization, structural branches or loops, or transformation-aware containers.
314
+
315
+ ## Reference routing
316
+
317
+ Open only the smallest reference that owns the decision.
318
+
319
+ ### Model construction and dynamics
320
+
321
+ | Reference | Open when |
322
+ |---|---|
323
+ | `built-in dynamic neuron model.md` | Selecting a built-in legacy neuron family, parameterization, or initialization. |
324
+ | `connecting neurons.md` | Selecting explicit, probabilistic, distance-based, or just-in-time connectivity. |
325
+ | `route activity through connectivity.md` | Choosing dense, sparse, event-driven, or just-in-time communication over an established connection structure. |
326
+ | `synaptic projections.md` | Composing presynaptic activity, communication, synaptic dynamics, output current, and postsynaptic targets. |
327
+ | `synpase properties.md` | Selecting synaptic kinetics, output type, alignment, delay, or short-term behavior. |
328
+ | `customize neuron and synpase.md` | Implementing a custom neuron, synapse, output, communication operator, or projection after built-ins are exhausted. |
329
+ | `integrators.md` | Selecting or defining ODE, SDE, fractional, or joint-equation integration for a custom model. |
330
+ | `infrastructure/delays.md` | Adding delayed Variables, accesses, or projection activity. |
331
+
332
+ ### Simulation and infrastructure
333
+
334
+ | Reference | Open when |
335
+ |---|---|
336
+ | `infrastructure/array creation and mechanics.md` | Creating, indexing, reshaping, combining, converting, or functionally updating legacy `brainpy.math` arrays. |
337
+ | `infrastructure/brainpy math environment setting.md` | Configuring `dt`, dtype, execution mode, precision, or platform. |
338
+ | `infrastructure/object oriented transformations and control flows.md` | Choosing object-aware JIT, gradients, Jacobians, vectorization, loops, scans, branches, or transformation-aware containers. |
339
+ | `infrastructure/Input generation.md` | Constructing sectioned, ramped, oscillatory, noisy, or spike-train stimuli. |
340
+ | `infrastructure/More about simulation.md` | Configuring `DSRunner` inputs, monitors, reset, repeated rollouts, prediction axes, or parameter-exploration execution. |
341
+ | `infrastructure/Parallel experiment execution.md` | Running independent simulations with CPU workers or JAX mapping and controlling batch memory. |
342
+ | `infrastructure/Multi-device array sharding.md` | Sharding one legacy array computation across multiple devices rather than mapping independent experiments. |
343
+
344
+ ### Training
345
+
346
+ | Reference | Open when |
347
+ |---|---|
348
+ | `training/trainingworkflows.md` | Choosing and executing offline ridge, online RLS or FORCE, BPTT, or a custom gradient loop. |
349
+ | `training/trainer library.md` | Selecting a trainer family or exact constructor and fit/predict lifecycle. |
350
+ | `training/prebuilt neural network layers.md` | Selecting a legacy trainable dense, recurrent, convolutional, normalization, pooling, or activation layer. |
351
+ | `training/parameter initializers.md` | Selecting an initializer for trainable parameters or model state. |
352
+ | `training/loss library.md` | Selecting a loss after output orientation and reduction are established. |
353
+ | `training/optimizers.md` | Selecting a legacy optimizer, scheduler, registration pattern, or update lifecycle. |
354
+ | `training/surrogate gradients.md` | Training a hard-threshold spiking model that needs a legacy surrogate derivative. |
355
+
356
+ ### Analysis
357
+
358
+ | Reference | Open when |
359
+ |---|---|
360
+ | `analysis.md` | Selecting and executing low-dimensional phase-plane, bifurcation, fast-slow, or high-dimensional fixed- and slow-point analysis. |
361
+
362
+ ## Boundaries and common failures
363
+
364
+ - Do not mix this workflow with `brainpy.state`, BrainState, BrainUnit, or Braintools APIs.
365
+
366
+ ## Official sources
367
+
368
+ - https://brainpy.readthedocs.io/quickstart/simulation.html
369
+ - https://brainpy.readthedocs.io/tutorial_simulation/simulation_dsrunner.html
370
+ - https://brainpy.readthedocs.io/quickstart/training.html
371
+ - https://brainpy.readthedocs.io/tutorial_math/variables.html
372
+ - https://brainpy.readthedocs.io/core_concept/brainpy_transform_concept.html
373
+ - https://brainpy.readthedocs.io/quickstart/analysis.html
@@ -0,0 +1,150 @@
1
+ # Legacy BrainPy built-in neuron models
2
+
3
+ Use this reference to select, initialize, run, and modify a built-in legacy `brainpy.dyn` point-neuron model. Use `customize neuron and synpase.md` when the required equations, state transitions, or spike rule are not represented by the built-in families.
4
+
5
+ ## Choose the neuron family
6
+
7
+ Choose the simplest family that contains the state variables and firing behavior required by the scientific question; suffix variants change input/refractory handling without changing the base model family.
8
+
9
+ | Base family | Use when |
10
+ |---|---|
11
+ | `bp.dyn.Lif` | A one-state leaky integrate-and-fire model is sufficient. |
12
+ | `bp.dyn.ExpIF` | Spike initiation needs an exponential voltage term. |
13
+ | `bp.dyn.AdExIF` | Exponential spike initiation and an adaptation state are required. |
14
+ | `bp.dyn.QuaIF` | Spike initiation is represented by quadratic voltage dynamics. |
15
+ | `bp.dyn.AdQuaIF` | Quadratic voltage dynamics need an adaptation state. |
16
+ | `bp.dyn.Gif` | A generalized integrate-and-fire model needs dynamic currents or threshold adaptation. |
17
+ | `bp.dyn.Izhikevich` | A compact two-state model must reproduce varied firing patterns. |
18
+ | `bp.dyn.HH` | Full Hodgkin-Huxley sodium, potassium, and leak gating is required. |
19
+ | `bp.dyn.MorrisLecar` | Two-dimensional conductance dynamics are sufficient for excitability or oscillation studies. |
20
+ | `bp.dyn.WangBuzsakiHH` | The modified Hodgkin-Huxley formulation used for fast-spiking interneurons is required. |
21
+
22
+ ### Choose a suffix variant
23
+
24
+ The reduced-neuron families expose systematic variants; select the behavior explicitly instead of treating the names as interchangeable aliases.
25
+
26
+ | Variant | Meaning |
27
+ |---|---|
28
+ | `Family` | Base model. |
29
+ | `FamilyLTC` | Liquid time-constant form of the base model. |
30
+ | `FamilyRef` | Base model with refractory-period state and `tau_ref`. |
31
+ | `FamilyRefLTC` | Liquid time-constant form with refractory-period state. |
32
+
33
+ These four forms are available for `Lif`, `ExpIF`, `AdExIF`, `QuaIF`, `AdQuaIF`, `Gif`, and `Izhikevich`. Conductance-based models expose `HH`/`HHLTC`, `MorrisLecar`/`MorrisLecarLTC`, and `WangBuzsakiHH`/`WangBuzsakiHHLTC`.
34
+
35
+ Use a `Ref` variant only when a refractory period is part of the model. Use the base variant when reset alone is sufficient.
36
+
37
+ ## Set population shape
38
+
39
+ `size` defines the number or logical arrangement of neurons; `keep_size=True` preserves a multidimensional logical shape in state variables.
40
+
41
+ | Form | Result |
42
+ |---|---|
43
+ | `bp.dyn.HH(1)` | One neuron with one-dimensional state of length 1. |
44
+ | `bp.dyn.HH(10)` | A flat population of 10 neurons. |
45
+ | `bp.dyn.HH((10, 10), keep_size=True)` | A population whose state keeps shape `(10, 10)`. |
46
+ | `bp.dyn.HH((5, 4, 2), keep_size=True)` | A population whose state keeps shape `(5, 4, 2)`. |
47
+
48
+ Choose `keep_size=True` only when spatial or logical axes carry meaning. Flattened population state is simpler for ordinary connection operators.
49
+
50
+ ## Initialize parameters and state
51
+
52
+ Built-in constructors accept shared scalars, per-neuron arrays, initializer objects, or callables for parameters and state initialization.
53
+
54
+ | Form | Use when |
55
+ |---|---|
56
+ | `gNa=120.0` | Every neuron shares one parameter value. |
57
+ | `gNa=bm.asarray([...])` | Each neuron has an explicit parameter value. The array must match the population shape. |
58
+ | `gNa=bp.init.Uniform(100.0, 140.0)` | Values should be sampled by a reusable initializer. |
59
+ | `gNa=lambda shape: bm.random.uniform(100.0, 140.0, shape)` | Initialization needs custom shape-dependent logic. |
60
+ | `V_initializer=bp.init.Uniform(-70.0, -60.0)` | State should start from a distribution. |
61
+
62
+ ```python
63
+ import brainpy as bp
64
+ import brainpy.math as bm
65
+
66
+ neurons = bp.dyn.HH(
67
+ size=3,
68
+ gNa=bp.init.Uniform(min_val=110.0, max_val=130.0),
69
+ V_initializer=bp.init.Uniform(min_val=-70.0, max_val=-60.0),
70
+ method='exp_auto',
71
+ )
72
+
73
+ assert neurons.V.shape == (3,)
74
+ assert neurons.gNa.shape == (3,)
75
+ ```
76
+
77
+ Use initializer arguments for initial state and ordinary model parameters for equation constants. Do not overwrite a state `Variable` with a plain array after construction.
78
+
79
+ ## Run and monitor a built-in model
80
+
81
+ `DSRunner` supplies one input per step and records selected state variables; monitor names must match variables exposed by the chosen model.
82
+
83
+ | API | Description |
84
+ |---|---|
85
+ | `bp.DSRunner(model, monitors=[...], inputs=...)` | Bind the neuron group, monitor variables, and input policy. |
86
+ | `runner.run(duration)` | Run for a duration using configured inputs. |
87
+ | `runner.run(inputs=array)` | Consume a time-indexed input array; its leading length determines the rollout length. |
88
+ | `runner.mon[name]` | Return a `(time, population...)` monitor history. |
89
+
90
+ ```python
91
+ import brainpy as bp
92
+ import brainpy.math as bm
93
+
94
+ bm.set_dt(0.1)
95
+
96
+ neurons = bp.dyn.MorrisLecar(
97
+ 3,
98
+ V_initializer=bp.init.Uniform(-70.0, -60.0),
99
+ )
100
+ runner = bp.DSRunner(neurons, monitors=['V', 'W'])
101
+
102
+ inputs = bm.ones(int(100.0 / bm.get_dt())) * 100.0
103
+ runner.run(inputs=inputs)
104
+
105
+ assert runner.mon['V'].shape == (1000, 3)
106
+ assert runner.mon['W'].shape == (1000, 3)
107
+ ```
108
+
109
+ Check the model API before choosing monitor names: reduced models commonly expose `V` and `spike`, while conductance-based models may expose gating variables such as `m`, `h`, `n`, or `W`.
110
+
111
+ ## Change a parameter during simulation
112
+
113
+ Ordinary constructor parameters are static under object-oriented JIT; wrap a parameter in `bm.Variable` only when it must change between or during compiled runs.
114
+
115
+ ```python
116
+ import brainpy as bp
117
+ import brainpy.math as bm
118
+
119
+ neurons = bp.dyn.HH(
120
+ 1,
121
+ gNa=bm.Variable(bm.asarray([120.0])),
122
+ )
123
+ runner = bp.DSRunner(neurons, monitors=['V'])
124
+
125
+ current = bm.ones(int(50.0 / bm.get_dt())) * 6.0
126
+ runner.run(inputs=current)
127
+
128
+ neurons.gNa[:] = 50.0
129
+ runner.run(inputs=current, reset_state=True)
130
+ ```
131
+
132
+ **Invariant:** Mark a changing parameter as `Variable` at construction. Replacing a static array or scalar after tracing does not reliably change compiled dynamics.
133
+
134
+ ## Model-selection checks
135
+
136
+ - Use a reduced model for network-scale questions unless ion-channel gating is itself part of the hypothesis.
137
+ - Use adaptation families only when the adaptation state is needed in the analysis or fit.
138
+ - Use refractory variants only when the refractory interval is specified or scientifically relevant.
139
+ - Verify constructor defaults against the intended parameterization; class-family similarity does not make defaults interchangeable.
140
+ - Validate firing threshold, reset, initial voltage, integration method, and applied current before comparing models.
141
+ - Compare spike statistics and voltage ranges, not only whether the simulation completes.
142
+
143
+ ## Routing
144
+
145
+ Open `customize neuron and synpase.md` when implementing new equations, reset logic, or state variables. Open `integrators.md` when selecting or configuring the ODE/SDE integrator. Open `brainpy legacy workflow.md` for networks, runner lifecycle, training, and analysis routing.
146
+
147
+ ## Sources mirrored
148
+
149
+ - https://brainpy.readthedocs.io/apis/brainpy.dyn.neurons.html
150
+ - https://brainpy.readthedocs.io/tutorial_building/overview_of_dynamic_model.html