brainx-skill 1.0.6 → 1.0.9
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 +10 -8
- package/adapters/gemini.js +7 -0
- package/adapters/opencode.js +7 -0
- package/adapters/windsurf.js +7 -0
- package/installation/lib/installer.js +4 -1
- package/manifest.json +6 -1
- package/package.json +8 -2
- package/skills/braincell/SKILL.md +182 -0
- package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +273 -0
- package/skills/braincell/references/channel-library.md +85 -0
- package/skills/braincell/references/ion-library.md +87 -0
- package/skills/braincell/references/mixions-for-adaptation.md +81 -0
- package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
- package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
- package/skills/braincell/references/multicompartment/filter-function-library.md +154 -0
- package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
- package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
- package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +260 -0
- package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
- package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
- package/skills/braincell/references/scripts/channel_ablation.py +61 -0
- package/skills/braincell/references/scripts/fi_curve.py +68 -0
- package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
- package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
- package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
- package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
- package/skills/braincell/references/solver-library-with-effects.md +188 -0
- package/skills/brainevent/SKILL.md +268 -0
- package/skills/brainevent/references/connectivity-variants.md +312 -0
- package/skills/brainevent/references/custom-operators-cpu.md +304 -0
- package/skills/brainevent/references/custom-operators-gpu.md +468 -0
- package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
- package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
- package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
- package/skills/brainevent/references/sparse-formats.md +182 -0
- package/skills/brainevent/references/synaptic-plasticity.md +285 -0
- package/skills/brainmass/SKILL.md +290 -0
- package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
- package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
- package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainmass/references/braintools/cogtask.md +190 -0
- package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
- package/skills/brainmass/references/braintools/metric.md +157 -0
- package/skills/brainmass/references/braintools/optimizer.md +187 -0
- package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
- package/skills/brainmass/references/braintools/surrogate.md +151 -0
- package/skills/brainmass/references/coupling-network-api.md +148 -0
- package/skills/brainmass/references/datasets-api.md +72 -0
- package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
- package/skills/brainmass/references/forward-observation-api.md +131 -0
- package/skills/brainmass/references/horn-task-training.md +199 -0
- package/skills/brainmass/references/modellibrary.md +104 -0
- package/skills/brainmass/references/noiseprocesses.md +121 -0
- package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
- package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
- package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
- package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
- package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
- package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
- package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
- package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
- package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
- package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
- package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
- package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
- package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
- package/skills/brainmass/references/visualization-analysis-api.md +130 -0
- package/skills/brainpy-state/SKILL.md +232 -0
- package/skills/brainpy-state/references/array-creation.md +158 -0
- package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
- package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
- package/skills/brainpy-state/references/braintools/metric.md +152 -0
- package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
- package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
- package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
- package/skills/brainpy-state/references/component-selection.md +273 -0
- package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
- package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
- package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
- package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
- package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
- package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
- package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
- package/skills/brainpy-state/references/projection-patterns.md +125 -0
- package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
- package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
- package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
- package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
- package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
- package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
- package/skills/brainstate/SKILL.md +1 -1
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
- package/skills/brainstate/references/collective_model_operations.md +9 -9
- package/skills/brainstate/references/extension_mechanisms.md +12 -1
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
- package/skills/brainstate/references/model-interop-and-migration.md +11 -1
- package/skills/brainstate/references/size-inference-variations.md +11 -0
- package/skills/brainstate/references/state-graph-operations.md +13 -15
- package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
- package/skills/brainx-general-guard/SKILL.md +68 -0
- package/skills/brainstate/references/braintools-optimizer-reference.md +0 -133
- package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# BrainPy projection delay protocol
|
|
2
|
+
|
|
3
|
+
Use this reference after choosing a native `brainpy.state` projection when presynaptic spikes or continuous values must reach the target after an axonal or synaptic transmission delay. This reference owns BrainPy projection integration; use the general BrainState delay protocol for arbitrary history buffers, named delay taps, delayed feedback State, or manual retrieval.
|
|
4
|
+
|
|
5
|
+
## Choose the delay integration point
|
|
6
|
+
|
|
7
|
+
Delay the signal before communication. Choose the API from how the projection receives that signal:
|
|
8
|
+
|
|
9
|
+
| Signal path | Use when | Call contract |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| `AlignPostProj(..., delay=delay)` | The step pushes a spike/event array directly into an AlignPost projection. | Call `proj(signal)`; the projection delays the supplied presynaptic input before `comm`. |
|
|
12
|
+
| `CurrentProj(..., delay=delay)` | The step pushes a continuous presynaptic value through communication and output conversion without synaptic dynamics. | Call `proj(signal)`; the projection delays the supplied value before `comm`. |
|
|
13
|
+
| `pre.prefetch("V").delay.at(delay)` | The projection pulls from a built-in neuron, which stores membrane potential rather than a separate historical spike State. | Build the projection once with the delayed prefetch and a spike decoder, then call `proj()` with no explicit signal. |
|
|
14
|
+
| General `brainstate.nn.Delay` APIs | The task needs reusable buffers, multiple named taps, manual updates, step-based retrieval, round interpolation, or custom delayed State. | Leave the BrainPy projection path and use the general BrainState protocol. |
|
|
15
|
+
|
|
16
|
+
Do not combine a delayed prefetch with an explicit signal at update time. The projection either pulls its configured delayed source or delays the value passed to `proj(signal)`.
|
|
17
|
+
|
|
18
|
+
## Push a delayed signal
|
|
19
|
+
|
|
20
|
+
Use `delay=` for a direct-input `AlignPostProj` or `CurrentProj`. A scalar time applies one homogeneous delay; an `(N_pre,)` quantity applies one delay per presynaptic neuron.
|
|
21
|
+
|
|
22
|
+
| API | Behavior |
|
|
23
|
+
|---|---|
|
|
24
|
+
| `AlignPostProj(..., delay=None)` | Keep the zero-overhead undelayed path. |
|
|
25
|
+
| `AlignPostProj(..., delay=scalar_time)` | Delay every presynaptic element by the same duration. |
|
|
26
|
+
| `AlignPostProj(..., delay=per_pre_time)` | Apply heterogeneous axonal delays; the delay array must have shape `(N_pre,)`. |
|
|
27
|
+
| `CurrentProj(..., delay=...)` | Apply the same scalar or per-presynaptic delay contract to continuous direct input. |
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
proj = brainpy.state.AlignPostProj(
|
|
31
|
+
comm=brainstate.nn.EventFixedProb(
|
|
32
|
+
n_pre,
|
|
33
|
+
n_post,
|
|
34
|
+
conn_num=0.1,
|
|
35
|
+
conn_weight=0.5 * u.mS,
|
|
36
|
+
),
|
|
37
|
+
syn=brainpy.state.Expon.desc(n_post, tau=5.0 * u.ms),
|
|
38
|
+
out=brainpy.state.COBA.desc(E=0.0 * u.mV),
|
|
39
|
+
post=post,
|
|
40
|
+
delay=5.0 * u.ms,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# Inside the step, before post(...) integrates:
|
|
44
|
+
proj(pre.get_spike() != 0.0)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Sub-`dt` delays are linearly interpolated. `init_state()` sizes the buffer from `ceil(max(delay) / dt)`, so establish `dt` before State initialization and do not change it during that initialized run.
|
|
48
|
+
|
|
49
|
+
## Pull a delayed neuron signal
|
|
50
|
+
|
|
51
|
+
Use delayed prefetch when the projection owns presynaptic extraction. Built-in neurons expose historical `V`, not a separate stored spike history, so delay `V` and re-derive the spike from the delayed voltage.
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
proj = brainpy.state.AlignPostProj(
|
|
55
|
+
pre.prefetch("V").delay.at(5.0 * u.ms),
|
|
56
|
+
lambda voltage: pre.get_spike(voltage) != 0.0,
|
|
57
|
+
comm=brainstate.nn.EventFixedProb(
|
|
58
|
+
n_pre,
|
|
59
|
+
n_post,
|
|
60
|
+
conn_num=0.1,
|
|
61
|
+
conn_weight=0.5 * u.mS,
|
|
62
|
+
),
|
|
63
|
+
syn=brainpy.state.Expon.desc(n_post, tau=5.0 * u.ms),
|
|
64
|
+
out=brainpy.state.COBA.desc(E=0.0 * u.mV),
|
|
65
|
+
post=post,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
# The projection pulls the delayed voltage and decodes its spike.
|
|
69
|
+
proj()
|
|
70
|
+
pre(drive)
|
|
71
|
+
post(0.0 * u.mA)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Keep the projection-before-post order. The delayed signal must be communicated before `post(...)` integrates the current step.
|
|
75
|
+
|
|
76
|
+
## Initialize, reset, and verify
|
|
77
|
+
|
|
78
|
+
1. Enter `brainstate.environ.context(dt=...)`.
|
|
79
|
+
2. Construct the network and delay-bearing projection.
|
|
80
|
+
3. Call `brainstate.nn.init_all_states(net)` so neural State and delay buffers are initialized together.
|
|
81
|
+
4. Run time through `brainstate.transform.for_loop`.
|
|
82
|
+
5. For every independent rollout, call `init_all_states()` again.
|
|
83
|
+
6. Compare otherwise identical undelayed, short-delay, and long-delay runs; monitor the presynaptic spike and projection conductance/current to verify the expected arrival-time shift before interpreting postsynaptic spikes.
|
|
84
|
+
|
|
85
|
+
Do not validate a delay only from postsynaptic spike time. Membrane integration, thresholding, refractory State, and other inputs can shift or suppress the postsynaptic spike even when the transmission delay is correct.
|
|
86
|
+
|
|
87
|
+
## General BrainState boundary
|
|
88
|
+
|
|
89
|
+
Open the official BrainState [Delay Protocol](https://brainx.chaobrain.com/brainstate/tutorials/brain_dynamics/02_synaptic_delays.html) when implementing `brainstate.nn.Delay`, `brainstate.nn.DelayAccess`, `brainstate.nn.StateWithDelay`, rotation versus concatenation buffers, named entries, manual `update(value)`, `retrieve_at_step`, `retrieve_at_time`, or linear-versus-round interpolation. Those mechanisms are more general than BrainPy projection delays and should not be reconstructed inside a projection unless the projection APIs cannot express the required history.
|
|
90
|
+
|
|
91
|
+
## Official sources
|
|
92
|
+
|
|
93
|
+
- `https://brainx.chaobrain.com/brainpy-state/brainpy-style/howto/sim-delays.html`
|
|
94
|
+
- `https://brainx.chaobrain.com/brainpy-state/apis/generated/brainpy.state.AlignPostProj.html`
|
|
95
|
+
- `https://brainx.chaobrain.com/brainpy-state/apis/generated/brainpy.state.CurrentProj.html`
|
|
96
|
+
- `https://brainx.chaobrain.com/brainstate/tutorials/brain_dynamics/02_synaptic_delays.html`
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
# BrainState control-flow patterns
|
|
2
|
+
|
|
3
|
+
Use this reference when loops or branches must preserve BrainState `State`
|
|
4
|
+
effects under JAX transformations, or when reverse-mode differentiation through
|
|
5
|
+
a long rollout exhausts memory. Use the root skill for `State`, `.value`,
|
|
6
|
+
Modules, gradients, and JIT fundamentals.
|
|
7
|
+
|
|
8
|
+
## Choose the primitive
|
|
9
|
+
|
|
10
|
+
| API | Use when |
|
|
11
|
+
|---|---|
|
|
12
|
+
| `scan(...)` | An explicit carry must thread through recurrent steps or accumulation while per-step outputs are collected. |
|
|
13
|
+
| `checkpointed_scan(...)` | Reverse-mode differentiation through a long carried sequence makes activation memory the bottleneck. |
|
|
14
|
+
| `for_loop(...)` | Per-step outputs must be collected while iteration-to-iteration effects live in Module `State` instead of an explicit carry. |
|
|
15
|
+
| `checkpointed_for_loop(...)` | A long State-driven differentiated rollout exhausts memory and the body needs no explicit carry. |
|
|
16
|
+
| `while_loop(...)` | Iteration continues until a runtime condition becomes false and reverse-mode gradients are not required. |
|
|
17
|
+
| `bounded_while_loop(...)` | Conditional iteration needs reverse-mode gradients, an iteration safety bound, or predictable compilation. |
|
|
18
|
+
| `cond(...)` | A scalar predicate selects one of two lazily executed branches. |
|
|
19
|
+
| `switch(...)` | An integer selects one of several callables and out-of-range indices may be clamped. |
|
|
20
|
+
| `ifelse(...)` | Mutually exclusive predicates express `if`/`elif`/`else`, with a final `True` condition as the default branch. |
|
|
21
|
+
|
|
22
|
+
Source: [Control flow](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html).
|
|
23
|
+
|
|
24
|
+
## Run fixed-length sequences
|
|
25
|
+
|
|
26
|
+
Fixed-length loop transforms slice inputs along axis 0, preserve tracked State
|
|
27
|
+
updates, and stack each step's output along a new leading axis.
|
|
28
|
+
|
|
29
|
+
| API | Description |
|
|
30
|
+
|---|---|
|
|
31
|
+
| `scan(f, init, xs, length=None, reverse=False, unroll=1, pbar=None)` | Use when `f(carry, x)` must return `(new_carry, output)`; it returns the final carry and stacked outputs. |
|
|
32
|
+
| `for_loop(f, *xs, length=None, reverse=False, unroll=1, pbar=None)` | Use when `f(*x)` needs no explicit carry; it slices every input along axis 0 and returns stacked outputs. |
|
|
33
|
+
| `checkpointed_scan(f, init, xs, length=None, base=16, pbar=None)` | Use the `scan` contract with gradient checkpointing; it returns the same carry and output structure while rematerializing intermediate activations during the backward pass. |
|
|
34
|
+
| `checkpointed_for_loop(f, *xs, length=None, base=16, pbar=None)` | Use the `for_loop` contract with gradient checkpointing; it returns the same stacked output structure while rematerializing intermediate activations during the backward pass. |
|
|
35
|
+
|
|
36
|
+
Use `scan` when the carry is an ordinary function value. Use `for_loop` when
|
|
37
|
+
iteration-to-iteration effects already live in Module `State`:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import jax.numpy as jnp
|
|
41
|
+
import brainstate
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Accumulator(brainstate.nn.Module):
|
|
45
|
+
def __init__(self):
|
|
46
|
+
super().__init__()
|
|
47
|
+
self.total = brainstate.ShortTermState(jnp.array(0.0))
|
|
48
|
+
self.count = brainstate.ShortTermState(jnp.array(0))
|
|
49
|
+
|
|
50
|
+
def update(self, x):
|
|
51
|
+
self.total.value = self.total.value + x
|
|
52
|
+
self.count.value = self.count.value + 1
|
|
53
|
+
return self.total.value / self.count.value
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
accumulator = Accumulator()
|
|
57
|
+
averages = brainstate.transform.for_loop(
|
|
58
|
+
accumulator.update,
|
|
59
|
+
jnp.array([1.0, 2.0, 3.0, 4.0]),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
assert jnp.allclose(averages, jnp.array([1.0, 1.5, 2.0, 2.5]))
|
|
63
|
+
assert accumulator.count.value == 4
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
**Invariant:** A scalar body result produces shape `(steps,)`; a body result of
|
|
67
|
+
shape `(d,)` produces shape `(steps, d)`. Pass `reverse=True` to traverse inputs
|
|
68
|
+
in reverse, `unroll` to control loop unrolling, and either an update frequency
|
|
69
|
+
or `ProgressBar` through `pbar` when progress reporting is required.
|
|
70
|
+
|
|
71
|
+
## Checkpoint long training rollouts
|
|
72
|
+
|
|
73
|
+
Checkpointed loops preserve the forward result but trade backward-pass
|
|
74
|
+
recomputation for lower activation memory, so place the checkpointed loop
|
|
75
|
+
inside the differentiated loss.
|
|
76
|
+
|
|
77
|
+
| API | Description |
|
|
78
|
+
|---|---|
|
|
79
|
+
| `checkpointed_for_loop(f, *xs, base=16)` | Use as a drop-in replacement for `for_loop` when a long State-driven BPTT rollout causes out-of-memory failures. |
|
|
80
|
+
| `checkpointed_scan(f, init, xs, base=16)` | Use as a drop-in replacement for `scan` when the differentiated rollout carries an explicit recurrent value. |
|
|
81
|
+
| `brainstate.transform.grad(loss_fn, grad_states, return_value=True)` | Differentiate the loss containing the checkpointed loop; it returns gradients keyed like `grad_states` and the loss from the same pass. |
|
|
82
|
+
| `brainstate.transform.jit(train_step)` | Compile the complete state initialization, differentiated rollout, and parameter update as one training step. |
|
|
83
|
+
|
|
84
|
+
This training pattern keeps the source how-to's ordinary and checkpointed paths
|
|
85
|
+
adjacent so the memory strategy is a construction-time choice:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
import brainpy
|
|
89
|
+
import brainstate
|
|
90
|
+
import braintools
|
|
91
|
+
import brainunit as u
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class SNN(brainstate.nn.Module):
|
|
95
|
+
def __init__(self, n_in, n_rec, n_out):
|
|
96
|
+
super().__init__()
|
|
97
|
+
self.input = brainstate.nn.Sequential(
|
|
98
|
+
brainstate.nn.Linear(
|
|
99
|
+
n_in,
|
|
100
|
+
n_rec,
|
|
101
|
+
w_init=braintools.init.KaimingNormal(unit=u.mA),
|
|
102
|
+
b_init=braintools.init.ZeroInit(unit=u.mA),
|
|
103
|
+
),
|
|
104
|
+
brainpy.state.Expon(
|
|
105
|
+
n_rec,
|
|
106
|
+
tau=5.0 * u.ms,
|
|
107
|
+
g_initializer=braintools.init.Constant(0.0 * u.mA),
|
|
108
|
+
),
|
|
109
|
+
)
|
|
110
|
+
self.recurrent = brainpy.state.LIF(
|
|
111
|
+
n_rec,
|
|
112
|
+
tau=20.0 * u.ms,
|
|
113
|
+
V_rest=0.0 * u.mV,
|
|
114
|
+
V_reset=0.0 * u.mV,
|
|
115
|
+
V_th=1.0 * u.mV,
|
|
116
|
+
spk_fun=braintools.surrogate.ReluGrad(),
|
|
117
|
+
)
|
|
118
|
+
self.readout = brainstate.nn.Linear(
|
|
119
|
+
n_rec,
|
|
120
|
+
n_out,
|
|
121
|
+
w_init=braintools.init.KaimingNormal(),
|
|
122
|
+
)
|
|
123
|
+
self.output = brainpy.state.Expon(
|
|
124
|
+
n_out,
|
|
125
|
+
tau=10.0 * u.ms,
|
|
126
|
+
g_initializer=braintools.init.Constant(0.0),
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
def update(self, spikes):
|
|
130
|
+
spikes = self.recurrent(self.input(spikes))
|
|
131
|
+
return self.output(self.readout(spikes))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def make_train_step(
|
|
135
|
+
net,
|
|
136
|
+
x_data,
|
|
137
|
+
y_data,
|
|
138
|
+
batch_size,
|
|
139
|
+
*,
|
|
140
|
+
use_checkpoint=True,
|
|
141
|
+
base=16,
|
|
142
|
+
):
|
|
143
|
+
params = net.states(brainstate.ParamState)
|
|
144
|
+
optimizer = braintools.optim.Adam(lr=2e-3)
|
|
145
|
+
optimizer.register_trainable_weights(params)
|
|
146
|
+
|
|
147
|
+
def loss_fn():
|
|
148
|
+
if use_checkpoint:
|
|
149
|
+
predictions = brainstate.transform.checkpointed_for_loop(
|
|
150
|
+
net.update,
|
|
151
|
+
x_data,
|
|
152
|
+
base=base,
|
|
153
|
+
)
|
|
154
|
+
else:
|
|
155
|
+
predictions = brainstate.transform.for_loop(
|
|
156
|
+
net.update,
|
|
157
|
+
x_data,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
logits = u.math.mean(predictions, axis=0)
|
|
161
|
+
return braintools.metric.softmax_cross_entropy_with_integer_labels(
|
|
162
|
+
logits,
|
|
163
|
+
y_data,
|
|
164
|
+
).mean()
|
|
165
|
+
|
|
166
|
+
@brainstate.transform.jit
|
|
167
|
+
def train_step():
|
|
168
|
+
brainstate.nn.init_all_states(net, batch_size=batch_size)
|
|
169
|
+
grads, loss = brainstate.transform.grad(
|
|
170
|
+
loss_fn,
|
|
171
|
+
params,
|
|
172
|
+
return_value=True,
|
|
173
|
+
)()
|
|
174
|
+
optimizer.update(grads)
|
|
175
|
+
return loss
|
|
176
|
+
|
|
177
|
+
return train_step
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
with brainstate.environ.context(dt=1.0 * u.ms):
|
|
181
|
+
n_in, n_rec, n_out = 80, 8, 2
|
|
182
|
+
num_steps, batch_size = 400, 64
|
|
183
|
+
x_data = (
|
|
184
|
+
brainstate.random.rand(num_steps, batch_size, n_in)
|
|
185
|
+
< 5.0 * u.Hz * brainstate.environ.get_dt()
|
|
186
|
+
).astype(float)
|
|
187
|
+
y_data = u.math.asarray(
|
|
188
|
+
brainstate.random.rand(batch_size) < 0.5,
|
|
189
|
+
dtype=int,
|
|
190
|
+
)
|
|
191
|
+
net = SNN(n_in, n_rec, n_out)
|
|
192
|
+
train_step = make_train_step(
|
|
193
|
+
net,
|
|
194
|
+
x_data,
|
|
195
|
+
y_data,
|
|
196
|
+
batch_size=batch_size,
|
|
197
|
+
use_checkpoint=True,
|
|
198
|
+
base=16,
|
|
199
|
+
)
|
|
200
|
+
loss = train_step()
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Use plain `for_loop` or `scan` by default. Switch only when reverse-mode
|
|
204
|
+
gradients through a long rollout make activation memory the binding constraint.
|
|
205
|
+
Tune `base` by measuring peak memory and step time: it controls checkpoint
|
|
206
|
+
granularity, so lower memory requires more backward recomputation.
|
|
207
|
+
|
|
208
|
+
**Invariant:** Initialize recurrent State before each rollout, keep the
|
|
209
|
+
checkpointed loop inside `loss_fn`, differentiate that loss, then JIT the whole
|
|
210
|
+
training step. Checkpointing changes the memory/compute profile, not the
|
|
211
|
+
predictions or loss contract.
|
|
212
|
+
|
|
213
|
+
Source: [How to train through long rollouts without exhausting memory](https://brainx.chaobrain.com/brainpy-state/brainpy-style/howto/train-long-rollouts-checkpoint.html).
|
|
214
|
+
|
|
215
|
+
## Run conditional iteration
|
|
216
|
+
|
|
217
|
+
Conditional loops preserve a fixed loop-value structure; choose the bounded
|
|
218
|
+
form when reverse-mode differentiation or an explicit iteration ceiling
|
|
219
|
+
matters.
|
|
220
|
+
|
|
221
|
+
| API | Description |
|
|
222
|
+
|---|---|
|
|
223
|
+
| `while_loop(cond_fun, body_fun, init_val)` | Use for an unknown iteration count without reverse-mode gradients; `cond_fun` must only read State, while State writes belong in `body_fun`. |
|
|
224
|
+
| `bounded_while_loop(cond_fun, body_fun, init_val, *, max_steps, base=16)` | Use when the loop needs reverse-mode differentiation or a hard upper bound; it stops when the condition is false or `max_steps` is reached. |
|
|
225
|
+
|
|
226
|
+
```python
|
|
227
|
+
import jax.numpy as jnp
|
|
228
|
+
import brainstate
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class Counter(brainstate.nn.Module):
|
|
232
|
+
def __init__(self):
|
|
233
|
+
super().__init__()
|
|
234
|
+
self.steps = brainstate.ShortTermState(jnp.array(0))
|
|
235
|
+
|
|
236
|
+
def increment(self, value):
|
|
237
|
+
self.steps.value = self.steps.value + 1
|
|
238
|
+
return value + 1
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
counter = Counter()
|
|
242
|
+
result = brainstate.transform.while_loop(
|
|
243
|
+
lambda value: value < 5,
|
|
244
|
+
counter.increment,
|
|
245
|
+
jnp.array(0),
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
assert result == 5
|
|
249
|
+
assert counter.steps.value == 5
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
**Invariant:** `cond_fun` must not mutate State, and every body result must keep
|
|
253
|
+
the loop value's PyTree structure, shape, and dtype stable. Do not use
|
|
254
|
+
`while_loop` for reverse-mode gradients; provide `max_steps` and use
|
|
255
|
+
`bounded_while_loop`.
|
|
256
|
+
|
|
257
|
+
For `bounded_while_loop`, `base` controls its recursive lowering rather than
|
|
258
|
+
gradient-checkpoint spacing. Larger values compile faster but can run slightly
|
|
259
|
+
slower; smaller values compile slower but can run faster.
|
|
260
|
+
|
|
261
|
+
## Select conditional branches
|
|
262
|
+
|
|
263
|
+
Branch transforms execute only the selected callable while tracking its State
|
|
264
|
+
reads and writes.
|
|
265
|
+
|
|
266
|
+
| API | Description |
|
|
267
|
+
|---|---|
|
|
268
|
+
| `cond(pred, true_fun, false_fun, *operands)` | Use for two branches selected by a boolean or numeric scalar; both branches must return the same PyTree structure. |
|
|
269
|
+
| `switch(index, branches, *operands)` | Use for integer-indexed multi-way branching; it clamps the index to `[0, len(branches) - 1]`. |
|
|
270
|
+
| `ifelse(conditions, branches, *operands, check_cond=True)` | Use for mutually exclusive predicates; with checking enabled, it verifies that exactly one condition is true. |
|
|
271
|
+
|
|
272
|
+
```python
|
|
273
|
+
import jax.numpy as jnp
|
|
274
|
+
import brainstate
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
class BranchTracker(brainstate.nn.Module):
|
|
278
|
+
def __init__(self):
|
|
279
|
+
super().__init__()
|
|
280
|
+
self.positive = brainstate.ShortTermState(jnp.array(0))
|
|
281
|
+
self.nonpositive = brainstate.ShortTermState(jnp.array(0))
|
|
282
|
+
|
|
283
|
+
def double(self, x):
|
|
284
|
+
self.positive.value = self.positive.value + 1
|
|
285
|
+
return x * 2
|
|
286
|
+
|
|
287
|
+
def halve(self, x):
|
|
288
|
+
self.nonpositive.value = self.nonpositive.value + 1
|
|
289
|
+
return x / 2
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
tracker = BranchTracker()
|
|
293
|
+
result = brainstate.transform.cond(
|
|
294
|
+
jnp.array(3.0) > 0,
|
|
295
|
+
tracker.double,
|
|
296
|
+
tracker.halve,
|
|
297
|
+
jnp.array(3.0),
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
assert result == 6
|
|
301
|
+
assert tracker.positive.value == 1
|
|
302
|
+
assert tracker.nonpositive.value == 0
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
For `ifelse`, use a final `True` predicate to encode the default branch:
|
|
306
|
+
|
|
307
|
+
```python
|
|
308
|
+
result = brainstate.transform.ifelse(
|
|
309
|
+
[x > 10, x > 5, True],
|
|
310
|
+
[large_fn, medium_fn, small_fn],
|
|
311
|
+
x,
|
|
312
|
+
)
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
**Invariant:** Keep branch return PyTrees compatible, and put branch-specific
|
|
316
|
+
State writes inside the branch callable. Do not use Python `if`, `for`, or
|
|
317
|
+
`while` when the decision or iteration count depends on traced JAX values.
|
|
318
|
+
|
|
319
|
+
## Common failures
|
|
320
|
+
|
|
321
|
+
- Do not select a checkpointed loop for forward-only execution; its memory
|
|
322
|
+
benefit applies during gradient computation.
|
|
323
|
+
- Do not expect checkpointing to reduce memory without extra backward
|
|
324
|
+
computation.
|
|
325
|
+
- Do not mutate State from a `while_loop` condition.
|
|
326
|
+
- Do not differentiate through `while_loop` with reverse mode; use
|
|
327
|
+
`bounded_while_loop`.
|
|
328
|
+
- Do not return incompatible structures from alternative branches.
|
|
329
|
+
- Do not assume `switch` rejects an invalid index; it clamps the index.
|
|
330
|
+
|
|
331
|
+
## Sources
|
|
332
|
+
|
|
333
|
+
- [Control flow](https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html) supplies the primitive contracts, selection rules, State behavior, loop-output semantics, checkpoint tradeoff, and branch invariants.
|
|
334
|
+
- [How to train through long rollouts without exhausting memory](https://brainx.chaobrain.com/brainpy-state/brainpy-style/howto/train-long-rollouts-checkpoint.html) supplies the BPTT checkpoint placement, compiled training-step workflow, and `base` tuning application.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# Braintools data preprocessing
|
|
2
|
+
|
|
3
|
+
Use this reference to convert continuous values, event streams, or temporal
|
|
4
|
+
features into spike representations and to combine binary spike tensors. Use
|
|
5
|
+
`braintools.cogtask` for phase-structured behavioral trials and
|
|
6
|
+
`braintools.input` for injected-current waveforms.
|
|
7
|
+
|
|
8
|
+
## Choose an encoder
|
|
9
|
+
|
|
10
|
+
Choose the representation from the information the downstream model must
|
|
11
|
+
preserve.
|
|
12
|
+
|
|
13
|
+
| Encoder family | Use when | Important result |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| Latency | Magnitude should control time to first spike | Larger normalized values spike earlier. |
|
|
16
|
+
| Rate or Poisson | Magnitude should control spike frequency | Returns a time-major spike train whose empirical rate represents the input. |
|
|
17
|
+
| Population | A scalar should activate overlapping receptive fields | Expands each scalar across a neuron population. |
|
|
18
|
+
| Bernoulli | Each time bin should be sampled independently | Converts normalized values into per-bin spike probabilities. |
|
|
19
|
+
| Delta | Only meaningful temporal changes should emit spikes | Detects threshold-crossing differences between successive samples. |
|
|
20
|
+
| Step current | A spiking neuron should receive an analog current level | Returns current values rather than a binary spike code. |
|
|
21
|
+
| Spike count | The window must contain an exact input-dependent count | Places a bounded number of spikes randomly or regularly. |
|
|
22
|
+
| Temporal | A discrete value should select a precise timing pattern | Maps values to synchronized temporal templates. |
|
|
23
|
+
| Rank order | Relative feature ordering matters more than absolute scale | Emits higher-ranked features before lower-ranked features. |
|
|
24
|
+
|
|
25
|
+
## Spike encoders
|
|
26
|
+
|
|
27
|
+
All encoder objects are reusable callables. Pass the input as the first argument
|
|
28
|
+
and the number of encoded timesteps as `n_time=`.
|
|
29
|
+
|
|
30
|
+
| API | Description |
|
|
31
|
+
|---|---|
|
|
32
|
+
| `LatencyEncoder(min_val=None, max_val=None, method='log', threshold=0.01, clip=False, tau=1 * u.ms, normalize=False, first_spk_time=0 * u.ms, epsilon=1e-7)` | Use for time-to-first-spike coding. Normalize inputs when they are not already in `[0, 1]`; larger values produce earlier spikes. |
|
|
33
|
+
| `RateEncoder(gain=100.0, method='linear', min_rate=0.0, max_rate=None, normalize=False, min_val=None, max_val=None)` | Use when firing rate should vary with input intensity. Select the mapping with `method` and constrain rates deliberately. |
|
|
34
|
+
| `PoissonEncoder(time_window=1000.0, normalize=False, max_rate=100.0)` | Use when an input rate should generate Poisson-distributed spikes. Increase the observation window before judging whether empirical counts match the requested rate. |
|
|
35
|
+
| `PopulationEncoder(n_neurons, min_val=0.0, max_val=1.0, sigma=None, max_rate=100.0)` | Use to encode each scalar with overlapping population receptive fields. Set the represented range and population width explicitly. |
|
|
36
|
+
| `BernoulliEncoder(scale=1.0, normalize=True, min_val=None, max_val=None)` | Use for independent Bernoulli sampling at every time step. Ensure the resulting probabilities remain valid after scaling. |
|
|
37
|
+
| `DeltaEncoder(threshold=0.1, positive_only=False, absolute=False, normalize=True)` | Use for change detection in a temporal signal. Configure sign handling so negative changes are either retained, suppressed, or folded by absolute value. |
|
|
38
|
+
| `StepCurrentEncoder(current_scale=10.0, offset=0.0, normalize=True, min_val=None, max_val=None)` | Use to turn features into constant injected-current levels for integrate-and-fire neurons. The result is an analog current code, not a spike tensor. |
|
|
39
|
+
| `SpikeCountEncoder(max_spikes=10, distribution='random', normalize=True)` | Use when input magnitude should determine an exact bounded spike count. Choose random or regular placement with `distribution`. |
|
|
40
|
+
| `TemporalEncoder(n_patterns, pattern_length=10, jitter=0.1)` | Use when values select reusable temporal spike patterns. Set `jitter` according to the timing variability the model should tolerate. |
|
|
41
|
+
| `RankOrderEncoder(use_values=True, normalize=True, invert=False)` | Use when feature rank determines spike order. Use `invert=True` only when low-valued features must spike first. |
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import jax.numpy as jnp
|
|
45
|
+
from braintools import LatencyEncoder
|
|
46
|
+
|
|
47
|
+
values = jnp.array([0.02, 0.5, 1.0])
|
|
48
|
+
encoder = LatencyEncoder(method="linear", normalize=True)
|
|
49
|
+
spikes = encoder(values, n_time=5)
|
|
50
|
+
|
|
51
|
+
assert spikes.shape == (5, 3)
|
|
52
|
+
assert jnp.argmax(spikes[:, 2]) < jnp.argmax(spikes[:, 1])
|
|
53
|
+
assert jnp.argmax(spikes[:, 1]) < jnp.argmax(spikes[:, 0])
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
**Invariant:** treat the leading axis as encoded time. Validate normalization,
|
|
57
|
+
time-window length, and stochastic variability before comparing encoders.
|
|
58
|
+
|
|
59
|
+
## Spike operations
|
|
60
|
+
|
|
61
|
+
Use these element-wise operations only on boolean or binary-compatible spike
|
|
62
|
+
tensors with broadcast-compatible shapes.
|
|
63
|
+
|
|
64
|
+
| API | Description |
|
|
65
|
+
|---|---|
|
|
66
|
+
| `spike_bitwise_or(x, y)` | Return binary OR, implemented as `x + y - x * y`. |
|
|
67
|
+
| `spike_bitwise_and(x, y)` | Return binary AND, implemented as element-wise multiplication. |
|
|
68
|
+
| `spike_bitwise_iand(x, y)` | Return inverse AND, documented as `(NOT x) AND y`. |
|
|
69
|
+
| `spike_bitwise_not(x)` | Invert a binary spike tensor. |
|
|
70
|
+
| `spike_bitwise_xor(x, y)` | Return XOR between two spike tensors. |
|
|
71
|
+
| `spike_bitwise_ixor(x, y)` | Apply the documented inverse-XOR operation. |
|
|
72
|
+
| `spike_bitwise(x, y, op)` | Dispatch by `op` over `'or'`, `'and'`, `'iand'`, `'xor'`, and `'ixor'`. |
|
|
73
|
+
|
|
74
|
+
Do not use these helpers as fuzzy arithmetic on rates or arbitrary continuous
|
|
75
|
+
arrays; their formulas assume binary values.
|
|
76
|
+
|
|
77
|
+
## Official source
|
|
78
|
+
|
|
79
|
+
- `https://brainx.chaobrain.com/braintools/apis/braintools.html`
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# Braintools metrics
|
|
2
|
+
|
|
3
|
+
Use this reference to select supervised losses and neuroscience metrics for
|
|
4
|
+
classification, regression, spike trains, local field potentials, correlation,
|
|
5
|
+
connectivity, and pairwise comparison. Verify input orientation, units, and
|
|
6
|
+
reduction before treating any returned array as a scalar objective.
|
|
7
|
+
|
|
8
|
+
## Choose a metric family
|
|
9
|
+
|
|
10
|
+
| Task | Use | Important constraint |
|
|
11
|
+
|---|---|---|
|
|
12
|
+
| Independent binary or multilabel classification | Sigmoid binary cross entropy or focal loss | Logits and labels must have broadcast-compatible class structure. |
|
|
13
|
+
| Mutually exclusive classes | Softmax cross entropy | Choose one-hot/probability labels or the integer-label variant explicitly. |
|
|
14
|
+
| Continuous fitting | Squared, absolute, Huber, log-cosh, or cosine losses | Set `reduction` rather than assuming a scalar result. |
|
|
15
|
+
| Spike timing | Victor-Purpura or van Rossum distance | Inputs are spike-time trains, not dense spike matrices. |
|
|
16
|
+
| Population spiking | Firing-rate and synchrony metrics | Dense spike matrices are time-major unless the API says otherwise. |
|
|
17
|
+
| LFP spectrum or coupling | PSD, coherence, PAC, CSD, entropy, or phase coherence | Pass the sample interval as `dt`, not sampling frequency as `fs`. |
|
|
18
|
+
| Functional connectivity | Correlation and connectivity functions | Time series use `(num_time, num_signals)`. |
|
|
19
|
+
|
|
20
|
+
## Classification losses
|
|
21
|
+
|
|
22
|
+
| API | Description |
|
|
23
|
+
|---|---|
|
|
24
|
+
| `sigmoid_binary_cross_entropy(logits, labels)` | Use for independent binary classes; returns element-wise sigmoid cross entropy. |
|
|
25
|
+
| `softmax_cross_entropy(logits, labels)` | Use for mutually exclusive classes represented by one-hot or probability labels. |
|
|
26
|
+
| `softmax_cross_entropy_with_integer_labels(logits, labels)` | Use the more direct integer-index form for mutually exclusive classes. Validate every label yourself. |
|
|
27
|
+
| `hinge_loss(...)` | Use for binary margin classification. |
|
|
28
|
+
| `perceptron_loss(...)` | Use for the binary perceptron objective. |
|
|
29
|
+
| `multiclass_hinge_loss(...)` | Use for a multiclass margin objective. |
|
|
30
|
+
| `multiclass_perceptron_loss(...)` | Use for a multiclass perceptron objective. |
|
|
31
|
+
| `poly_loss_cross_entropy(...)` | Use when the specified method requires PolyLoss cross entropy. |
|
|
32
|
+
| `kl_divergence(...)` | Compare probability distributions. |
|
|
33
|
+
| `kl_divergence_with_log_targets(...)` | Use when predictions and targets are already in log space. |
|
|
34
|
+
| `convex_kl_divergence(...)` | Use when the convex KL variant is required. |
|
|
35
|
+
| `ctc_loss(...)` | Use for sequence alignment without frame-level labels. |
|
|
36
|
+
| `ctc_loss_with_forward_probs(...)` | Use when the CTC forward probabilities are also needed. |
|
|
37
|
+
| `sigmoid_focal_loss(...)` | Use for class imbalance among independent binary targets. |
|
|
38
|
+
| `nll_loss(...)` | Use with log-probability classification outputs. |
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
import jax.numpy as jnp
|
|
42
|
+
from braintools.metric import (
|
|
43
|
+
softmax_cross_entropy_with_integer_labels,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
logits = jnp.array([
|
|
47
|
+
[2.0, 1.0, 0.1],
|
|
48
|
+
[0.5, 2.5, 0.3],
|
|
49
|
+
])
|
|
50
|
+
labels = jnp.array([0, 1])
|
|
51
|
+
|
|
52
|
+
per_example = softmax_cross_entropy_with_integer_labels(logits, labels)
|
|
53
|
+
loss = jnp.mean(per_example)
|
|
54
|
+
assert loss.ndim == 0
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**Critical exception:** JAX gather silently clamps out-of-range integer labels
|
|
58
|
+
in `softmax_cross_entropy_with_integer_labels`. Validate
|
|
59
|
+
`0 <= labels < logits.shape[-1]`; the function does not raise for invalid
|
|
60
|
+
labels.
|
|
61
|
+
|
|
62
|
+
## Regression and pairwise metrics
|
|
63
|
+
|
|
64
|
+
| API | Description |
|
|
65
|
+
|---|---|
|
|
66
|
+
| `squared_error(predictions, targets=None, axis=None, reduction='none')` | Use for element-wise squared error; choose `mean` or another supported reduction explicitly when a scalar is required. |
|
|
67
|
+
| `absolute_error(...)` | Use for element-wise absolute error. |
|
|
68
|
+
| `l1_loss(...)` | Use for mean absolute-error behavior according to its axis/reduction options. |
|
|
69
|
+
| `l2_loss(...)` | Use for squared L2 loss. |
|
|
70
|
+
| `l2_norm(...)` | Return the L2 norm of prediction error. |
|
|
71
|
+
| `safe_norm(...)` | Use when a differentiable lower bound must prevent an unstable zero norm. |
|
|
72
|
+
| `huber_loss(predictions, targets=None, delta=1.0, axis=None, reduction='none')` | Use for quadratic small residuals and linear large residuals; tune `delta` in target units. |
|
|
73
|
+
| `log_cosh(...)` | Use for a smooth robust regression loss. |
|
|
74
|
+
| `cosine_similarity(...)` | Compare vector direction. |
|
|
75
|
+
| `cosine_distance(...)` | Return the corresponding cosine distance. |
|
|
76
|
+
| `pairwise_cosine_similarity(X, Y, ...)` | Return all pairwise cosine similarities between sample sets. |
|
|
77
|
+
| `pairwise_cosine_distance(X, Y, ...)` | Return all pairwise cosine distances between sample sets. |
|
|
78
|
+
|
|
79
|
+
Do not conflate element-wise loss with final optimization reduction. Preserve
|
|
80
|
+
batch and time axes until the scientific loss definition determines how to
|
|
81
|
+
reduce them.
|
|
82
|
+
|
|
83
|
+
## Correlation and functional connectivity
|
|
84
|
+
|
|
85
|
+
| API | Description |
|
|
86
|
+
|---|---|
|
|
87
|
+
| `cross_correlation(spikes, bin, dt)` | Calculate a cross-correlation synchrony index from a time-major spike matrix. |
|
|
88
|
+
| `voltage_fluctuation(voltages)` | Estimate synchrony from population voltage variance. |
|
|
89
|
+
| `matrix_correlation(a, b)` | Correlate upper-triangular entries of two square matrices. |
|
|
90
|
+
| `weighted_correlation(x, y, weights)` | Compute weighted Pearson correlation for two one-dimensional series. |
|
|
91
|
+
| `functional_connectivity(activities)` | Return the pairwise Pearson correlation matrix for `(num_time, num_signals)` data; NaNs are replaced with zero. |
|
|
92
|
+
| `functional_connectivity_dynamics(activities, window_size, step_size)` | Compare sliding-window connectivity matrices to produce functional-connectivity dynamics. |
|
|
93
|
+
|
|
94
|
+
## Spike-train metrics
|
|
95
|
+
|
|
96
|
+
| API | Description |
|
|
97
|
+
|---|---|
|
|
98
|
+
| `raster_plot(spikes, times)` | Extract neuron indices and spike times from a dense spike matrix; this is a metric/data helper, not the visualization API. |
|
|
99
|
+
| `firing_rate(spikes, width, dt=None)` | Average across neurons and smooth population rate with a rectangular window of physical width. |
|
|
100
|
+
| `victor_purpura_distance(spike_times_1, spike_times_2, cost_factor=1.0)` | Measure edit cost from insertions, deletions, and temporal shifts. |
|
|
101
|
+
| `van_rossum_distance(spike_times_1, spike_times_2, tau=...)` | Compare exponentially filtered spike trains. |
|
|
102
|
+
| `spike_train_synchrony(spikes, window_size, dt=None)` | Compute SPIKE-style synchronization on a population matrix. |
|
|
103
|
+
| `burst_synchrony_index(spikes, dt=None, ...)` | Measure co-occurring burst events. |
|
|
104
|
+
| `phase_locking_value(spikes, reference_freq, dt=None, ...)` | Measure spike phase locking to a reference oscillation. |
|
|
105
|
+
| `spike_time_tiling_coefficient(spikes, dt=None, tau=...)` | Compute STTC within a temporal tolerance. |
|
|
106
|
+
| `correlation_index(spikes, window_size, dt=None)` | Compute a windowed spike-train correlation index. |
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
import brainunit as u
|
|
110
|
+
from braintools.metric import firing_rate, spike_train_synchrony
|
|
111
|
+
|
|
112
|
+
# Shape: (num_time, num_neurons)
|
|
113
|
+
rate = firing_rate(spikes, width=10 * u.ms, dt=1 * u.ms)
|
|
114
|
+
synchrony = spike_train_synchrony(
|
|
115
|
+
spikes,
|
|
116
|
+
window_size=5 * u.ms,
|
|
117
|
+
dt=1 * u.ms,
|
|
118
|
+
)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Keep dense spike matrices and lists of spike times distinct. Distance metrics
|
|
122
|
+
consume event times; population rate and synchrony metrics consume matrices.
|
|
123
|
+
|
|
124
|
+
## Local field potential analysis
|
|
125
|
+
|
|
126
|
+
| API | Description |
|
|
127
|
+
|---|---|
|
|
128
|
+
| `unitary_LFP(times, spikes, neuron_type, seed=None, ...)` | Construct unitary LFP contributions from spikes; use the documented `'exc'` or `'inh'` neuron type. |
|
|
129
|
+
| `power_spectral_density(lfp, dt, nperseg=None, noverlap=None, freq_range=None)` | Return one-sided Welch frequencies and PSD. |
|
|
130
|
+
| `coherence_analysis(signal1, signal2, dt, ...)` | Return frequency-resolved magnitude-squared coherence. |
|
|
131
|
+
| `phase_amplitude_coupling(lfp, dt, phase_freq_range, amplitude_freq_range, ...)` | Return Tort modulation index plus phase-bin details. |
|
|
132
|
+
| `theta_gamma_coupling(lfp, dt, ...)` | Return theta-gamma coupling using standard bands. |
|
|
133
|
+
| `current_source_density(lfp, electrode_spacing, axis=0, ...)` | Estimate laminar CSD along the electrode axis. |
|
|
134
|
+
| `spectral_entropy(lfp, dt, ...)` | Return normalized spectral entropy. |
|
|
135
|
+
| `lfp_phase_coherence(lfp, dt, freq_band, ...)` | Compute pairwise phase coherence across channels. |
|
|
136
|
+
|
|
137
|
+
`power_spectral_density(..., freq_range=...)` uses boolean-mask indexing and
|
|
138
|
+
therefore has a data-dependent output length; that path is not JIT-compatible.
|
|
139
|
+
Compute the full spectrum inside JIT and filter outside when compilation is
|
|
140
|
+
required.
|
|
141
|
+
|
|
142
|
+
## Structured, ranking, and smoothing losses
|
|
143
|
+
|
|
144
|
+
| API | Description |
|
|
145
|
+
|---|---|
|
|
146
|
+
| `make_fenchel_young_loss(max_fun)` | Build a Fenchel-Young loss. `max_fun` must map one score vector to a scalar because it is vectorized with signature `(n)->()`. |
|
|
147
|
+
| `ranking_softmax_loss(scores, labels, ...)` | Use for list-wise learning-to-rank objectives. |
|
|
148
|
+
| `smooth_labels(labels, alpha=...)` | Apply label smoothing to one-hot targets. |
|
|
149
|
+
|
|
150
|
+
## Official source
|
|
151
|
+
|
|
152
|
+
- `https://brainx.chaobrain.com/braintools/apis/metric.html`
|