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.
- package/README.md +6 -0
- package/adapters/antigravity.js +8 -0
- package/installation/lib/installer.js +60 -20
- package/installation/lib/paths.js +41 -3
- package/installation/lib/prompts.js +13 -7
- package/manifest.json +2 -1
- package/package.json +3 -2
- package/skills/braincell/SKILL.md +1 -1
- package/skills/braincell/references/mixions-for-adaptation.md +26 -3
- package/skills/braincell/references/scripts/spike_frequency_adaptation.py +113 -53
- package/skills/brainevent/references/synaptic-plasticity.md +74 -230
- package/skills/brainmass/SKILL.md +11 -6
- package/skills/brainmass/references/batch-transform-acceleration.md +44 -3
- package/skills/brainmass/references/modellibrary.md +11 -0
- package/skills/brainmass/references/simulator-input-monitor-api.md +98 -0
- package/skills/brainpy-state/SKILL.md +20 -6
- package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +52 -1
- package/skills/brainpy-state/references/brainPy(legacy)/analysis.md +150 -0
- package/skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +373 -0
- package/skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +150 -0
- package/skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +175 -0
- package/skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +286 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +111 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +163 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +113 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +136 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +222 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +123 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +107 -0
- package/skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +185 -0
- package/skills/brainpy-state/references/brainPy(legacy)/integrators.md +181 -0
- package/skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +102 -0
- package/skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +147 -0
- package/skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +159 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +127 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +167 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +107 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +186 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +104 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +89 -0
- package/skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +253 -0
- package/skills/brainpy-state/references/braintools/connectivity.md +206 -0
- package/skills/brainpy-state/references/braintools/input-current.md +199 -0
- package/skills/brainpy-state/references/component-selection.md +20 -5
- package/skills/brainpy-state/references/projection-patterns.md +2 -0
- package/skills/brainpy-state/references/scripts/sound_localization.py +240 -0
- package/skills/brainstate/SKILL.md +1 -1
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +8 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +57 -7
- package/skills/brainstate/references/collective_model_operations.md +26 -27
- package/skills/braintrace/SKILL.md +161 -0
- package/skills/braintrace/references/Drtrl.md +179 -0
- package/skills/braintrace/references/ETP operators.md +161 -0
- package/skills/braintrace/references/algorithm selection.md +120 -0
- package/skills/braintrace/references/batching.md +150 -0
- package/skills/braintrace/references/compiler_internal.md +162 -0
- package/skills/braintrace/references/custom ETP primitives.md +200 -0
- package/skills/braintrace/references/custom algorithms.md +206 -0
- package/skills/braintrace/references/customizing_primitive_transforms.md +191 -0
- package/skills/braintrace/references/pp_pprop workflow.md +196 -0
- package/skills/braintrace/references/pre-built-braintrace-layer.md +149 -0
- package/skills/brainx-general-guard/SKILL.md +64 -21
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# Legacy BrainPy math environment settings
|
|
2
|
+
|
|
3
|
+
Use this reference to set or scope legacy `brainpy.math` integration step, computation mode, precision, default dtypes, platform, host-device count, and device-memory behavior. Set environment values before constructing models whose shapes or variables depend on them.
|
|
4
|
+
|
|
5
|
+
## Choose persistent or scoped settings
|
|
6
|
+
|
|
7
|
+
`bm.set(...)` changes process-wide defaults, while `bm.environment(...)` temporarily overrides selected settings and restores the previous environment on exit.
|
|
8
|
+
|
|
9
|
+
| API | Description |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `bm.set(mode=None, dt=None, x64=None, float_=None, int_=None, bool_=None, complex_=None, ...)` | Persist one or more defaults for subsequent legacy BrainPy work. |
|
|
12
|
+
| `bm.set_environment(...)` | Alias for setting the default computation environment. |
|
|
13
|
+
| `bm.environment(mode=None, dt=None, x64=None, float_=None, int_=None, bool_=None, complex_=None, ...)` | Scope selected settings with a context manager and restore prior values afterward. |
|
|
14
|
+
| `bm.batching_environment(dt=None, batch_size=1, ...)` | Scope `BatchingMode` and its batch size for batched prediction or readout fitting. |
|
|
15
|
+
| `bm.training_environment(dt=None, batch_size=1, ...)` | Scope `TrainingMode` and its batch size while constructing trainable models. |
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
import brainpy.math as bm
|
|
19
|
+
|
|
20
|
+
original_dt = bm.get_dt()
|
|
21
|
+
|
|
22
|
+
with bm.environment(dt=0.05, x64=True, float_=bm.float64):
|
|
23
|
+
assert bm.get_dt() == 0.05
|
|
24
|
+
assert bm.get_float() == bm.float64
|
|
25
|
+
# Construct and run the precision-sensitive model here.
|
|
26
|
+
|
|
27
|
+
assert bm.get_dt() == original_dt
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Use `bm.set(dt=...)` for a deliberate application default. Use a context when one experiment, training phase, or analysis needs a local override.
|
|
31
|
+
|
|
32
|
+
## Set integration step and mode
|
|
33
|
+
|
|
34
|
+
The integration step controls the default `dt` consumed by legacy integrators and `DSRunner`; the mode controls whether models allocate unbatched, batched, or trainable state.
|
|
35
|
+
|
|
36
|
+
| API | Description |
|
|
37
|
+
|---|---|
|
|
38
|
+
| `bm.set_dt(dt)` | Persist the default numerical integration step. |
|
|
39
|
+
| `bm.get_dt()` | Return the active integration step. |
|
|
40
|
+
| `bm.set_mode(mode)` | Persist a `NonBatchingMode`, `BatchingMode`, or `TrainingMode`. |
|
|
41
|
+
| `bm.get_mode()` | Return the active mode object. |
|
|
42
|
+
| `bm.nonbatching_mode` | Use for ordinary single-instance simulation. |
|
|
43
|
+
| `bm.batching_mode` | Use for batched execution without trainable-mode allocation. |
|
|
44
|
+
| `bm.training_mode` | Use when model construction must create trainable parameters. |
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
import brainpy as bp
|
|
48
|
+
import brainpy.math as bm
|
|
49
|
+
|
|
50
|
+
with bm.training_environment(dt=0.1, batch_size=32):
|
|
51
|
+
model = bp.dnn.Dense(20, 2)
|
|
52
|
+
assert isinstance(bm.get_mode(), bm.TrainingMode)
|
|
53
|
+
|
|
54
|
+
assert isinstance(bm.get_mode(), bm.NonBatchingMode)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**Invariant:** Enter batching or training mode before constructing mode-dependent layers. Changing mode after construction does not retroactively change parameter roles or state shapes.
|
|
58
|
+
|
|
59
|
+
## Set precision and default dtypes
|
|
60
|
+
|
|
61
|
+
Enable x64 before constructing precision-sensitive arrays or analyzers; setting only a float default does not itself enable JAX 64-bit support.
|
|
62
|
+
|
|
63
|
+
| API | Description |
|
|
64
|
+
|---|---|
|
|
65
|
+
| `bm.enable_x64()` | Enable JAX 64-bit values for subsequent computation. |
|
|
66
|
+
| `bm.disable_x64()` | Disable JAX 64-bit values. |
|
|
67
|
+
| `bm.set_float(dtype)` | Set the default floating dtype. |
|
|
68
|
+
| `bm.get_float()` | Return the default floating dtype. |
|
|
69
|
+
| `bm.set_int(dtype)` | Set the default integer dtype. |
|
|
70
|
+
| `bm.get_int()` | Return the default integer dtype. |
|
|
71
|
+
| `bm.set_bool(dtype)` | Set the default boolean dtype. |
|
|
72
|
+
| `bm.get_bool()` | Return the default boolean dtype. |
|
|
73
|
+
| `bm.set_complex(dtype)` | Set the default complex dtype. |
|
|
74
|
+
| `bm.get_complex()` | Return the default complex dtype. |
|
|
75
|
+
| `bm.dftype()` | Return the active default float dtype. |
|
|
76
|
+
| `bm.ditype()` | Return the active default integer dtype. |
|
|
77
|
+
|
|
78
|
+
Use 64-bit computation for numerical dynamics analysis when root finding or eigenvalue classification is unstable at 32-bit precision. Keep 32-bit computation for normal simulation or training unless accuracy tests justify the added memory and compute cost.
|
|
79
|
+
|
|
80
|
+
## Select platform and host devices
|
|
81
|
+
|
|
82
|
+
Platform selection affects JAX backend initialization and must occur at program startup.
|
|
83
|
+
|
|
84
|
+
| API | Description |
|
|
85
|
+
|---|---|
|
|
86
|
+
| `bm.set_platform(platform)` | Select `'cpu'`, `'gpu'`, or `'tpu'`; call before arrays or compiled functions initialize the backend. |
|
|
87
|
+
| `bm.get_platform()` | Return the active platform name. |
|
|
88
|
+
| `bm.set_host_device_count(n)` | Expose `n` logical CPU devices so CPU `pmap` workflows can run. Configure before backend initialization. |
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
import brainpy.math as bm
|
|
92
|
+
|
|
93
|
+
# Put this at the start of the process, before model or array construction.
|
|
94
|
+
bm.set_platform('cpu')
|
|
95
|
+
assert bm.get_platform() == 'cpu'
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Do not call `set_platform()` in the middle of a process and assume existing arrays or compiled functions migrate to the new backend.
|
|
99
|
+
|
|
100
|
+
## Control device memory
|
|
101
|
+
|
|
102
|
+
Use memory controls only at explicit process boundaries or between large independent model runs.
|
|
103
|
+
|
|
104
|
+
| API | Description |
|
|
105
|
+
|---|---|
|
|
106
|
+
| `bm.clear_buffer_memory(platform=None, array=True, transform=True, compilation=False, object_name=False)` | Clear selected BrainPy/JAX buffers and caches, useful between models executed in a Python loop. |
|
|
107
|
+
| `bm.enable_gpu_memory_preallocation()` | Enable the configured JAX GPU preallocation behavior. |
|
|
108
|
+
| `bm.disable_gpu_memory_preallocation(release_memory=True)` | Allocate GPU memory on demand; this can reduce reserved memory but may increase fragmentation risk. |
|
|
109
|
+
|
|
110
|
+
Do not clear buffers inside a simulation step or training step. Cache clearing invalidates reuse and can dominate runtime.
|
|
111
|
+
|
|
112
|
+
## Common failures
|
|
113
|
+
|
|
114
|
+
- Do not set `dt` after constructing data or delays whose lengths were computed from the previous step.
|
|
115
|
+
- Do not create a model before entering `training_environment()` when its layers depend on training mode.
|
|
116
|
+
- Do not request `float64` without enabling x64 and then assume the request was honored.
|
|
117
|
+
- Do not select CPU/GPU/TPU after JAX has initialized its backend.
|
|
118
|
+
- Do not use persistent global settings for one local experiment when a restoring context is sufficient.
|
|
119
|
+
- Do not reuse another package's environment context; legacy `brainpy.math` keeps separate settings.
|
|
120
|
+
|
|
121
|
+
## Sources mirrored
|
|
122
|
+
|
|
123
|
+
- https://brainpy.readthedocs.io/apis/brainpy.math.environment.html
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# Legacy BrainPy delay buffers
|
|
2
|
+
|
|
3
|
+
Use this reference when a legacy `brainpy.math` model needs an explicit history
|
|
4
|
+
buffer indexed by simulation time or by integer simulation steps. Do not replace
|
|
5
|
+
these buffers with `brainpy.state` or BrainState delay APIs when maintaining a
|
|
6
|
+
legacy BrainPy model.
|
|
7
|
+
|
|
8
|
+
## Choose the delay coordinate
|
|
9
|
+
|
|
10
|
+
Choose the buffer from the coordinate used by the model to request history.
|
|
11
|
+
|
|
12
|
+
| API | Use when | Critical behavior |
|
|
13
|
+
|---|---|---|
|
|
14
|
+
| `bm.TimeDelay(delay_target, delay_len, before_t0=None, t0=0.0, dt=None, name=None, interp_method='linear_interp')` | The model requests an earlier value by absolute simulation time. | Stores `ceil(delay_len / dt) + 1` samples and interpolates off-grid requests by default. |
|
|
15
|
+
| `bm.LengthDelay(delay_target, delay_len, initial_delay_data=None, name=None, batch_axis=None, update_method='rotation')` | The model requests an earlier value by an integer number of steps. | Stores `delay_len + 1` samples; `retrieve(0)` is the latest value after an update. |
|
|
16
|
+
| `bm.NeuTimeDelay(...)` | Compatibility code names the neutral time-delay alias. | It is an alias of `TimeDelay`; do not choose it as a distinct mechanism. |
|
|
17
|
+
| `bm.NeuLenDelay(...)` | Compatibility code names the neutral length-delay alias. | It is an alias of `LengthDelay`; do not choose it as a distinct mechanism. |
|
|
18
|
+
|
|
19
|
+
Use `TimeDelay` when physical time and interpolation are part of the model. Use
|
|
20
|
+
`LengthDelay` when the delay has already been discretized into steps.
|
|
21
|
+
|
|
22
|
+
## Retrieve time-indexed history
|
|
23
|
+
|
|
24
|
+
`TimeDelay` tracks its own current time; call it with the absolute past time to
|
|
25
|
+
retrieve and call `update()` once whenever a new current sample enters the
|
|
26
|
+
history.
|
|
27
|
+
|
|
28
|
+
| API | Description |
|
|
29
|
+
|---|---|
|
|
30
|
+
| `delay(time, indices=None)` | Retrieve the value at absolute `time`; optionally select `indices` from the result. |
|
|
31
|
+
| `delay.update(value)` | Append the new current value and advance the buffer's current time by `dt`. |
|
|
32
|
+
| `delay.reset(delay_target, delay_len, t0=0.0, before_t0=None)` | Rebuild the history and restart its time coordinate. |
|
|
33
|
+
| `interp_method='linear_interp'` | Use for continuous off-grid retrieval; interpolate between adjacent stored samples. |
|
|
34
|
+
| `interp_method='round'` | Use when retrieval must snap to the nearest stored time step. |
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import brainpy.math as bm
|
|
38
|
+
|
|
39
|
+
delay = bm.TimeDelay(
|
|
40
|
+
bm.zeros(3),
|
|
41
|
+
delay_len=1.0,
|
|
42
|
+
dt=0.1,
|
|
43
|
+
before_t0=lambda t: t,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
# Before t0, the callable supplies a value broadcast to the target shape.
|
|
47
|
+
past = delay(-0.2)
|
|
48
|
+
assert past.shape == (3,)
|
|
49
|
+
assert bm.allclose(past, bm.array([-0.2, -0.2, -0.2]))
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The requested time must not exceed the buffer's current time and must remain
|
|
53
|
+
within the retained window. Supply `before_t0` when prehistory is not the
|
|
54
|
+
default initialized data. A callable receives the requested time; an array is
|
|
55
|
+
laid out as `(num_delay, ...)`, with the longest delay first.
|
|
56
|
+
|
|
57
|
+
## Retrieve step-indexed history
|
|
58
|
+
|
|
59
|
+
`LengthDelay` makes discrete delay semantics explicit: update the buffer with
|
|
60
|
+
the newest sample, then retrieve an integer number of steps into the past.
|
|
61
|
+
|
|
62
|
+
| API | Description |
|
|
63
|
+
|---|---|
|
|
64
|
+
| `delay.retrieve(delay_len, *indices)` | Retrieve an integer step offset and optionally index the stored value. |
|
|
65
|
+
| `delay.update(value=None)` | Insert `value`; when constructed from a `bm.Variable`, omit `value` to insert that variable's current value. |
|
|
66
|
+
| `delay.reset(delay_target, delay_len=None, initial_delay_data=None, batch_axis=None)` | Reinitialize the target, retained length, prehistory, and optional batch axis. |
|
|
67
|
+
| `bm.ROTATE_UPDATE` | Pass this `'rotation'` constant as `update_method`; use the default circular-buffer update. |
|
|
68
|
+
| `bm.CONCAT_UPDATE` | Pass this `'concat'` constant as `update_method`; use explicit concatenation when that storage behavior is required. |
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
import brainpy.math as bm
|
|
72
|
+
|
|
73
|
+
signal = bm.Variable(bm.array([0.0]))
|
|
74
|
+
delay = bm.LengthDelay(signal, delay_len=2)
|
|
75
|
+
|
|
76
|
+
signal.value = bm.array([1.0])
|
|
77
|
+
delay.update()
|
|
78
|
+
signal.value = bm.array([2.0])
|
|
79
|
+
delay.update()
|
|
80
|
+
|
|
81
|
+
assert bm.allclose(delay.retrieve(0), bm.array([2.0]))
|
|
82
|
+
assert bm.allclose(delay.retrieve(1), bm.array([1.0]))
|
|
83
|
+
assert bm.allclose(delay.retrieve(2), bm.array([0.0]))
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`delay_len` passed to `retrieve()` must be integer-valued and smaller than the
|
|
87
|
+
stored sample count. If `initial_delay_data` is an array, arrange its leading
|
|
88
|
+
axis as delays `1, 2, ..., delay_len`; this ordering changed in BrainPy 2.2.3.2,
|
|
89
|
+
so inspect old checkpoints before reusing their raw buffer arrays.
|
|
90
|
+
|
|
91
|
+
## Source-backed failures
|
|
92
|
+
|
|
93
|
+
- Construct either buffer from a BrainPy or JAX array, not an arbitrary Python
|
|
94
|
+
container.
|
|
95
|
+
- Establish `dt` before constructing `TimeDelay`; omitting `dt` captures the
|
|
96
|
+
current global BrainPy time step.
|
|
97
|
+
- Do not request fractional steps from `LengthDelay`; use `TimeDelay` when
|
|
98
|
+
interpolation is required.
|
|
99
|
+
- Do not update a history more than once per logical simulation step.
|
|
100
|
+
- Preserve the delay-buffer State when wrapping the containing legacy object in
|
|
101
|
+
`bm.jit`, `bm.for_loop`, or another object-oriented transformation.
|
|
102
|
+
|
|
103
|
+
## Official sources
|
|
104
|
+
|
|
105
|
+
- `https://brainpy.readthedocs.io/apis/brainpy.math.delayvars.html`
|
|
106
|
+
- Generated `TimeDelay`, `LengthDelay`, `NeuTimeDelay`, and `NeuLenDelay` pages
|
|
107
|
+
linked from that API index.
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
# Legacy BrainPy object-oriented transformations and control flows
|
|
2
|
+
|
|
3
|
+
Use this reference when a legacy BrainPy program mutates `bm.Variable` objects
|
|
4
|
+
inside JIT compilation, automatic differentiation, vectorization, branching, or
|
|
5
|
+
loops. Use `brainpy.math` object-aware transformations; do not translate the
|
|
6
|
+
program to `brainpy.state` or BrainState while maintaining its legacy contract.
|
|
7
|
+
|
|
8
|
+
## Make mutable values discoverable
|
|
9
|
+
|
|
10
|
+
`BrainPyObject` owns nested objects and `Variable` leaves so BrainPy's
|
|
11
|
+
transformations can separate mutable dynamic values from static Python
|
|
12
|
+
structure.
|
|
13
|
+
|
|
14
|
+
| API | Description |
|
|
15
|
+
|---|---|
|
|
16
|
+
| `bp.BrainPyObject(name=None)` | Subclass when an object owns mutable variables or child BrainPy objects that transformations must discover. |
|
|
17
|
+
| `bm.Variable(value_or_size, dtype=None, batch_axis=None, *, axis_names=None)` | Use for mutable dynamical values; read or replace the stored array through `.value`. |
|
|
18
|
+
| `bm.TrainVar(value_or_size, dtype=None, batch_axis=None, *, axis_names=None)` | Use to mark a mutable value as trainable for legacy gradient and optimizer workflows. |
|
|
19
|
+
| `bm.Parameter(value_or_size, dtype=None, batch_axis=None, *, axis_names=None)` | Use for a parameter pointer that is not selected as a `TrainVar`. |
|
|
20
|
+
| `bm.VariableView(value, index)` | Use when a transformed object must expose a view into part of another variable. |
|
|
21
|
+
| `bm.NodeList(seq=())` | Store child `BrainPyObject` instances in a transformation-aware sequence. |
|
|
22
|
+
| `bm.NodeDict(*args, check_unique=False, **kwargs)` | Store child `BrainPyObject` instances in a transformation-aware mapping. |
|
|
23
|
+
| `bm.VarList(seq=())` | Store variables in a transformation-aware sequence. |
|
|
24
|
+
| `bm.VarDict(*args, **kwargs)` | Store variables in a transformation-aware mapping. |
|
|
25
|
+
| `bm.function(f=None, nodes=None, dyn_vars=None, name=None)` | Wrap a Python function as a `BrainPyObject` while declaring captured nodes or dynamic variables. |
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import brainpy as bp
|
|
29
|
+
import brainpy.math as bm
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Accumulator(bp.BrainPyObject):
|
|
33
|
+
def __init__(self):
|
|
34
|
+
super().__init__()
|
|
35
|
+
self.total = bm.Variable(bm.zeros(1))
|
|
36
|
+
|
|
37
|
+
@bm.cls_jit
|
|
38
|
+
def __call__(self, value):
|
|
39
|
+
self.total.value += value
|
|
40
|
+
return self.total.value
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
accumulator = Accumulator()
|
|
44
|
+
assert bm.allclose(accumulator(2.0), bm.array([2.0]))
|
|
45
|
+
assert bm.allclose(accumulator(3.0), bm.array([5.0]))
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Assign child objects and variables to attributes or the transformation-aware
|
|
49
|
+
containers. A plain Python list or dictionary can hide mutable leaves from
|
|
50
|
+
legacy object traversal.
|
|
51
|
+
|
|
52
|
+
## Choose an object-aware transformation
|
|
53
|
+
|
|
54
|
+
These APIs mirror JAX transformations while also tracking variables owned by a
|
|
55
|
+
legacy BrainPy object.
|
|
56
|
+
|
|
57
|
+
| API | Description |
|
|
58
|
+
|---|---|
|
|
59
|
+
| `bm.jit(func, static_argnums=None, static_argnames=None, donate_argnums=(), inline=False, keep_unused=False, **kwargs)` | JIT-compile a pure function, bound method, `DynamicalSystem`, or `BrainPyObject` call while preserving discovered variable mutation. |
|
|
60
|
+
| `bm.cls_jit(...)` | Decorate a class method so the compiled callable remains bound to the instance. |
|
|
61
|
+
| `bm.grad(func=None, grad_vars=None, argnums=None, holomorphic=False, allow_int=False, has_aux=None, return_value=False)` | Differentiate a scalar-returning function with respect to captured variables, positional arguments, or both. |
|
|
62
|
+
| `bm.vector_grad(...)` | Use when the differentiated function has a vector-valued result. |
|
|
63
|
+
| `bm.jacrev(...)` | Compute a reverse-mode Jacobian for a function or class object. |
|
|
64
|
+
| `bm.jacobian(...)` | Use the legacy reverse-mode Jacobian alias. |
|
|
65
|
+
| `bm.jacfwd(...)` | Compute a forward-mode Jacobian. |
|
|
66
|
+
| `bm.hessian(...)` | Compute a dense Hessian. |
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
class Quadratic(bp.BrainPyObject):
|
|
70
|
+
def __init__(self):
|
|
71
|
+
super().__init__()
|
|
72
|
+
self.weight = bm.TrainVar(bm.array([1.0]))
|
|
73
|
+
|
|
74
|
+
def __call__(self, target):
|
|
75
|
+
return bm.mean((self.weight - target) ** 2)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
objective = Quadratic()
|
|
79
|
+
value_and_grad = bm.grad(
|
|
80
|
+
objective,
|
|
81
|
+
grad_vars=objective.weight,
|
|
82
|
+
return_value=True,
|
|
83
|
+
)
|
|
84
|
+
weight_grad, loss = value_and_grad(bm.array([3.0]))
|
|
85
|
+
|
|
86
|
+
assert weight_grad.shape == objective.weight.shape
|
|
87
|
+
assert loss.ndim == 0
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Use `grad_vars` for captured `Variable` objects and `argnums` for differentiable
|
|
91
|
+
positional arguments. When both are supplied, `bm.grad` returns variable and
|
|
92
|
+
argument gradients together. Set `return_value=True` only when the loss is also
|
|
93
|
+
needed; set `has_aux=True` only when the function returns auxiliary data in
|
|
94
|
+
addition to its scalar differentiable value.
|
|
95
|
+
|
|
96
|
+
## Choose a compiled conditional
|
|
97
|
+
|
|
98
|
+
Ordinary Python branching is valid only when its predicate is static during
|
|
99
|
+
tracing. Use structural control flow when the predicate depends on a traced
|
|
100
|
+
array or `bm.Variable`.
|
|
101
|
+
|
|
102
|
+
| API | Description |
|
|
103
|
+
|---|---|
|
|
104
|
+
| `bm.where(condition, x, y)` | Use for elementwise selection over scalars, vectors, or higher-dimensional arrays. |
|
|
105
|
+
| `bm.cond(pred, true_fun, false_fun, operands=())` | Use for one scalar boolean branch whose functions may read or mutate discovered variables. |
|
|
106
|
+
| `bm.ifelse(conditions, branches, operands=None)` | Use for an if/elif/else chain; provide one more branch than conditions for the final else case. |
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
class SignedStep(bp.BrainPyObject):
|
|
110
|
+
def __init__(self):
|
|
111
|
+
super().__init__()
|
|
112
|
+
self.total = bm.Variable(bm.zeros(1))
|
|
113
|
+
|
|
114
|
+
def __call__(self, predicate):
|
|
115
|
+
increment = bm.ifelse(
|
|
116
|
+
conditions=predicate,
|
|
117
|
+
branches=[lambda: 1.0, lambda: -1.0],
|
|
118
|
+
)
|
|
119
|
+
self.total.value += increment
|
|
120
|
+
return self.total.value
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
step = bm.jit(SignedStep())
|
|
124
|
+
step(bm.asarray(True))
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Do not write `if variable_condition:` inside `bm.jit`; traced boolean conversion
|
|
128
|
+
raises an error. Use `bm.where` when both choices are elementwise data and
|
|
129
|
+
`bm.cond` or `bm.ifelse` when branch functions own the computation.
|
|
130
|
+
|
|
131
|
+
## Choose a compiled loop
|
|
132
|
+
|
|
133
|
+
Structural loops keep tracing cost bounded and preserve legacy Variable
|
|
134
|
+
mutation without unrolling a long Python loop into the compiled program.
|
|
135
|
+
|
|
136
|
+
| API | Description |
|
|
137
|
+
|---|---|
|
|
138
|
+
| `bm.for_loop(body_fun, operands, reverse=False, unroll=1, jit=None, progress_bar=False)` | Iterate over axis 0 of one operand or matching operand PyTrees and stack every value returned by `body_fun`. |
|
|
139
|
+
| `bm.scan(body_fun, init, operands, reverse=False, unroll=1, remat=False, progress_bar=False)` | Use a `jax.lax.scan`-style explicit carry together with discovered variable mutation. |
|
|
140
|
+
| `bm.while_loop(body_fun, cond_fun, operands)` | Repeat while `cond_fun` is true; returned operands must preserve the input structure, shapes, and dtypes. |
|
|
141
|
+
| `bm.ProgressBar(freq=None, count=None, desc=None, ...)` | Configure progress reporting for a compiled `for_loop` or `scan` when callbacks are supported by the execution context. |
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
total = bm.Variable(bm.zeros(1))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def accumulate(value):
|
|
148
|
+
total.value += value
|
|
149
|
+
return total.value
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
history = bm.for_loop(
|
|
153
|
+
body_fun=accumulate,
|
|
154
|
+
operands=bm.arange(1.0, 5.0),
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
assert history.shape == (4, 1)
|
|
158
|
+
assert bm.allclose(total.value, bm.array([10.0]))
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
`for_loop` gathers outputs; those outputs are not the loop carry. By contrast,
|
|
162
|
+
`while_loop` returns updated operands and therefore must return what it
|
|
163
|
+
receives, with stable structure and array metadata. Prefer either structural
|
|
164
|
+
loop over a long Python loop inside `bm.jit`, which traces each iteration and
|
|
165
|
+
can make first-call compilation excessive.
|
|
166
|
+
|
|
167
|
+
## Source-backed failures
|
|
168
|
+
|
|
169
|
+
- Make a differentiated loss scalar. Use `vector_grad` or a Jacobian API when
|
|
170
|
+
the mathematical result is intentionally non-scalar.
|
|
171
|
+
- Keep array shapes and dtypes stable across every conditional branch and
|
|
172
|
+
`while_loop` iteration.
|
|
173
|
+
- Make all mutated variables discoverable through a `BrainPyObject`, declared
|
|
174
|
+
`dyn_vars`, or transformation-aware container.
|
|
175
|
+
- Do not mutate ordinary Python state and expect compiled execution to replay
|
|
176
|
+
that side effect on every call.
|
|
177
|
+
- Keep optimizer-owned variables in the transformed variable set when a legacy
|
|
178
|
+
optimizer update is JIT-compiled; open `../training/optimizers.md` for that lifecycle.
|
|
179
|
+
|
|
180
|
+
## Official sources
|
|
181
|
+
|
|
182
|
+
- `https://brainpy.readthedocs.io/apis/brainpy.math.oo_transform.html`
|
|
183
|
+
- `https://brainpy.readthedocs.io/tutorial_math/control_flows.html`
|
|
184
|
+
- Generated object, variable, transformation, and control-flow pages linked
|
|
185
|
+
from the official API index.
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
# Legacy BrainPy integrators
|
|
2
|
+
|
|
3
|
+
Use this child reference of `customize neuron and synpase.md` when a legacy
|
|
4
|
+
BrainPy neuron, synapse, or standalone differential equation needs a numerical
|
|
5
|
+
integrator. This reference covers `brainpy.odeint`, `brainpy.sdeint`,
|
|
6
|
+
`brainpy.fdeint`, and the legacy `brainpy.integrators` registry; it does not
|
|
7
|
+
cover `brainpy.state` or BrainCell solvers.
|
|
8
|
+
|
|
9
|
+
## Choose the equation family
|
|
10
|
+
|
|
11
|
+
Select the equation family before selecting a numerical method.
|
|
12
|
+
|
|
13
|
+
| API | Use when | Required model definition |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `bp.odeint(f=None, method=None, var_type=None, dt=None, name=None, show_code=False, state_delays=None, neutral_delays=None, **kwargs)` | State evolves under deterministic ordinary differential equations. | `f` returns one derivative per state variable. |
|
|
16
|
+
| `bp.sdeint(f=None, g=None, method=None, dt=None, name=None, show_code=False, var_type=None, intg_type=None, wiener_type=None, state_delays=None)` | State includes stochastic diffusion. | `f` defines drift and `g` defines diffusion; select Ito versus Stratonovich semantics deliberately. |
|
|
17
|
+
| `bp.fdeint(alpha, num_memory, inits, f=None, method=None, dt=None, name=None)` | State follows a fractional differential equation with finite retained memory. | Supply derivative order `alpha`, memory length, and initial values. |
|
|
18
|
+
| `bp.JointEq(*eqs)` | Several first-order derivative functions form one coupled system. | Put equations in the same order as the state results expected from the integrator. |
|
|
19
|
+
| `bp.IntegratorRunner(target, inits=None, dt=None, monitors=None, dyn_vars=None, jit=True, numpy_mon_after_run=True, progress_bar=True, args=None, dyn_args=None, fun_monitors=None)` | A standalone integrator needs a simulation loop, initial values, dynamic arguments, and monitors. | The target must be a constructed legacy BrainPy integrator. |
|
|
20
|
+
|
|
21
|
+
## Construct a deterministic integrator
|
|
22
|
+
|
|
23
|
+
`bp.odeint` converts a derivative function into a callable one-step integrator;
|
|
24
|
+
the state arguments come first, `t` marks time, and remaining arguments are
|
|
25
|
+
model inputs or parameters.
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import brainpy as bp
|
|
29
|
+
import brainpy.math as bm
|
|
30
|
+
|
|
31
|
+
a = 0.7
|
|
32
|
+
b = 0.8
|
|
33
|
+
tau = 12.5
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@bp.odeint(method='rk4', dt=0.04)
|
|
37
|
+
def integral(V, w, t, Iext):
|
|
38
|
+
dV = V - V * V * V / 3.0 - w + Iext
|
|
39
|
+
dw = (V + a - b * w) / tau
|
|
40
|
+
return dV, dw
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
V = bm.asarray(0.0)
|
|
44
|
+
w = bm.asarray(0.0)
|
|
45
|
+
V, w = integral(V, w, 0.0, 0.5)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Return derivatives in state-argument order. When several derivative functions
|
|
49
|
+
are easier to maintain separately, combine them with `bp.JointEq` and construct
|
|
50
|
+
one integrator from the joint equation.
|
|
51
|
+
|
|
52
|
+
## Select an ODE method
|
|
53
|
+
|
|
54
|
+
Use an explicit Runge-Kutta method for a general deterministic baseline, an
|
|
55
|
+
adaptive method when local error control is required, and exponential Euler
|
|
56
|
+
when the model's form benefits from its automatic-differentiation construction.
|
|
57
|
+
|
|
58
|
+
### Explicit Runge-Kutta methods
|
|
59
|
+
|
|
60
|
+
| API | Description |
|
|
61
|
+
|---|---|
|
|
62
|
+
| `bp.integrators.ode.Euler(...)` | Use for the simplest first-order explicit baseline. |
|
|
63
|
+
| `bp.integrators.ode.MidPoint(...)` | Use for the explicit midpoint method. |
|
|
64
|
+
| `bp.integrators.ode.Heun2(...)` | Use for second-order Heun integration. |
|
|
65
|
+
| `bp.integrators.ode.Ralston2(...)` | Use for second-order Ralston integration. |
|
|
66
|
+
| `bp.integrators.ode.RK2(...)` | Use for a generic second-order Runge-Kutta method. |
|
|
67
|
+
| `bp.integrators.ode.RK3(...)` | Use for classical third-order Runge-Kutta integration. |
|
|
68
|
+
| `bp.integrators.ode.Heun3(...)` | Use for third-order Heun integration. |
|
|
69
|
+
| `bp.integrators.ode.Ralston3(...)` | Use for third-order Ralston integration. |
|
|
70
|
+
| `bp.integrators.ode.SSPRK3(...)` | Use when the third-order strong-stability-preserving method is intended. |
|
|
71
|
+
| `bp.integrators.ode.RK4(...)` | Use for the classical fourth-order fixed-step baseline. |
|
|
72
|
+
| `bp.integrators.ode.Ralston4(...)` | Use for fourth-order Ralston integration. |
|
|
73
|
+
| `bp.integrators.ode.RK4Rule38(...)` | Use for the fourth-order 3/8-rule method. |
|
|
74
|
+
|
|
75
|
+
### Adaptive and exponential methods
|
|
76
|
+
|
|
77
|
+
| API | Description |
|
|
78
|
+
|---|---|
|
|
79
|
+
| `bp.integrators.ode.RKF12(...)` | Use for the embedded Fehlberg RK1(2) method. |
|
|
80
|
+
| `bp.integrators.ode.RKF45(...)` | Use for Runge-Kutta-Fehlberg integration. |
|
|
81
|
+
| `bp.integrators.ode.DormandPrince(...)` | Use for the Dormand-Prince embedded pair. |
|
|
82
|
+
| `bp.integrators.ode.CashKarp(...)` | Use for the Cash-Karp embedded pair. |
|
|
83
|
+
| `bp.integrators.ode.BogackiShampine(...)` | Use for the Bogacki-Shampine embedded pair. |
|
|
84
|
+
| `bp.integrators.ode.HeunEuler(...)` | Use for the Heun-Euler embedded pair. |
|
|
85
|
+
| `bp.integrators.ode.ExponentialEuler(...)` | Use for exponential Euler built with automatic differentiation. |
|
|
86
|
+
|
|
87
|
+
Pass a documented method name such as `'rk4'` through `bp.odeint(method=...)`.
|
|
88
|
+
Do not derive registry strings from class names. Inspect
|
|
89
|
+
`bp.integrators.ode.get_supported_methods()` when the installed legacy release
|
|
90
|
+
must determine the accepted names.
|
|
91
|
+
|
|
92
|
+
## Select an SDE method
|
|
93
|
+
|
|
94
|
+
Match the numerical method to the stochastic-integral convention and Wiener
|
|
95
|
+
process structure declared through `bp.sdeint`.
|
|
96
|
+
|
|
97
|
+
| API | Description |
|
|
98
|
+
|---|---|
|
|
99
|
+
| `bp.integrators.sde.Euler(...)` | Use for Euler integration under the supported Ito or Stratonovich convention. |
|
|
100
|
+
| `bp.integrators.sde.Heun(...)` | Use for the Euler-Heun Stratonovich scheme. |
|
|
101
|
+
| `bp.integrators.sde.Milstein(...)` | Use for Milstein integration under the supported Ito or Stratonovich convention. |
|
|
102
|
+
| `bp.integrators.sde.MilsteinGradFree(...)` | Use when the derivative-free Milstein variant is required. |
|
|
103
|
+
| `bp.integrators.sde.ExponentialEuler(...)` | Use for first-order explicit exponential Euler SDE integration. |
|
|
104
|
+
| `bp.integrators.sde.SRK1W1(...)` | Use for the documented weak order-2 scalar-Wiener SRK method. |
|
|
105
|
+
| `bp.integrators.sde.SRK2W1(...)` | Use for the documented strong order-1.5 scalar-noise SRK method. |
|
|
106
|
+
| `bp.integrators.sde.KlPl(...)` | Use only when this registered scalar-Wiener scheme is explicitly required. |
|
|
107
|
+
|
|
108
|
+
`Euler` and `ExponentialEuler` exist in both ODE and SDE namespaces. Keep the
|
|
109
|
+
namespace visible in prose and code so the equation family cannot be confused.
|
|
110
|
+
|
|
111
|
+
## Select an FDE method
|
|
112
|
+
|
|
113
|
+
Choose the fractional derivative definition before choosing the implementation.
|
|
114
|
+
|
|
115
|
+
| API | Description |
|
|
116
|
+
|---|---|
|
|
117
|
+
| `bp.integrators.fde.CaputoEuler(...)` | Use for one-step Euler integration of a Caputo fractional equation. |
|
|
118
|
+
| `bp.integrators.fde.CaputoL1Schema(...)` | Use for the L1 approximation of a Caputo fractional derivative. |
|
|
119
|
+
| `bp.integrators.fde.GLShortMemory(...)` | Use for a Riemann-Liouville equation approximated by the Grunwald-Letnikov short-memory principle. |
|
|
120
|
+
|
|
121
|
+
The FDE constructor requires `num_memory`; treat that value as part of the model
|
|
122
|
+
and validation plan, not merely a runtime optimization.
|
|
123
|
+
|
|
124
|
+
## Configure and extend the registries
|
|
125
|
+
|
|
126
|
+
| API | Description |
|
|
127
|
+
|---|---|
|
|
128
|
+
| `bp.integrators.ode.set_default_odeint(method)` | Set the process-wide default ODE method. Prefer an explicit `method=` in reusable model code. |
|
|
129
|
+
| `bp.integrators.ode.get_default_odeint()` | Inspect the process-wide default ODE method. |
|
|
130
|
+
| `bp.integrators.sde.set_default_sdeint(method)` | Set the process-wide default SDE method. |
|
|
131
|
+
| `bp.integrators.sde.get_default_sdeint()` | Inspect the process-wide default SDE method. |
|
|
132
|
+
| `bp.integrators.fde.set_default_fdeint(method)` | Set the process-wide default FDE method. |
|
|
133
|
+
| `bp.integrators.fde.get_default_fdeint()` | Inspect the process-wide default FDE method. |
|
|
134
|
+
| `bp.integrators.ode.register_ode_integrator(name, integrator)` | Register a custom ODE integrator under a method name. |
|
|
135
|
+
| `bp.integrators.sde.register_sde_integrator(name, integrator)` | Register a custom SDE integrator under a method name. |
|
|
136
|
+
| `bp.integrators.fde.register_fde_integrator(name, integrator)` | Register a custom FDE integrator under a method name. |
|
|
137
|
+
| `bp.integrators.ode.get_supported_methods()` | Inspect registered ODE method names. |
|
|
138
|
+
| `bp.integrators.sde.get_supported_methods()` | Inspect registered SDE method names. |
|
|
139
|
+
| `bp.integrators.fde.get_supported_methods()` | Inspect registered FDE method names. |
|
|
140
|
+
|
|
141
|
+
Register a custom implementation only when no built-in family expresses the
|
|
142
|
+
required numerical method. Keep process-wide default changes out of imported
|
|
143
|
+
library modules because they alter later integrator construction globally.
|
|
144
|
+
|
|
145
|
+
## Run and verify a standalone equation
|
|
146
|
+
|
|
147
|
+
Use `IntegratorRunner` when no `DynamicalSystem` owns the integration loop.
|
|
148
|
+
Supply constant arguments through `args`, time-varying arrays through
|
|
149
|
+
`dyn_args`, and inspect the named histories in `runner.mon`.
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
equations = bp.JointEq(
|
|
153
|
+
lambda V, t, w, I: V - V**3 / 3.0 - w + I,
|
|
154
|
+
lambda w, t, V, a, b: (V + a - b * w) / 12.5,
|
|
155
|
+
)
|
|
156
|
+
step = bp.odeint(equations, method='exp_auto')
|
|
157
|
+
|
|
158
|
+
runner = bp.IntegratorRunner(
|
|
159
|
+
step,
|
|
160
|
+
inits={'V': bm.zeros(4), 'w': bm.zeros(4)},
|
|
161
|
+
monitors=['V', 'w'],
|
|
162
|
+
)
|
|
163
|
+
runner.run(
|
|
164
|
+
100.0,
|
|
165
|
+
args={'a': 0.7, 'b': 0.8},
|
|
166
|
+
dyn_args={'I': bp.inputs.ramp_input(0.0, 1.0, 100.0)},
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
assert runner.mon.V.shape[0] == runner.mon.ts.shape[0]
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Verify convergence by rerunning at a smaller `dt` and comparing the scientific
|
|
173
|
+
observable, not only whether the integrator executes. For stochastic equations,
|
|
174
|
+
also fix the random source and compare distributions or summary statistics.
|
|
175
|
+
|
|
176
|
+
## Official sources
|
|
177
|
+
|
|
178
|
+
- `https://brainpy.readthedocs.io/apis/integrators.html`
|
|
179
|
+
- Generated `brainpy.odeint`, `brainpy.sdeint`, `brainpy.fdeint`,
|
|
180
|
+
`brainpy.JointEq`, and `brainpy.IntegratorRunner` pages linked by the official
|
|
181
|
+
API navigation.
|