brainx-skill 1.0.3 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +29 -64
  3. package/adapters/gemini.js +7 -0
  4. package/adapters/opencode.js +7 -0
  5. package/adapters/windsurf.js +7 -0
  6. package/{lib → installation/lib}/installer.js +8 -5
  7. package/manifest.json +7 -1
  8. package/package.json +25 -10
  9. package/skills/braincell/SKILL.md +182 -0
  10. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  11. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
  12. package/skills/braincell/references/channel-library.md +170 -0
  13. package/skills/braincell/references/ion-library.md +154 -0
  14. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  15. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  16. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  17. package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
  18. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  19. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  20. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  21. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
  22. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  23. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  24. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  25. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  26. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  27. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  28. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  29. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  30. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  31. package/skills/brainevent/SKILL.md +268 -0
  32. package/skills/brainevent/references/connectivity-variants.md +312 -0
  33. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  34. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  35. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  36. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  37. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  38. package/skills/brainevent/references/sparse-formats.md +182 -0
  39. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  40. package/skills/brainpy-state/SKILL.md +232 -0
  41. package/skills/brainpy-state/references/array-creation.md +158 -0
  42. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  43. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  44. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  45. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  46. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  47. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  48. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  49. package/skills/brainpy-state/references/component-selection.md +273 -0
  50. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  51. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  52. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  53. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  54. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  55. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  56. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  57. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  58. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  59. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  60. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  61. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  62. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  63. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  64. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  65. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  66. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  67. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  68. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  69. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  70. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  71. package/skills/brainstate/SKILL.md +399 -0
  72. package/skills/brainstate/agents/openai.yaml +4 -0
  73. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
  75. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
  76. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  77. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
  78. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
  79. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
  80. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
  81. package/skills/brainstate/references/collective_model_operations.md +195 -0
  82. package/skills/brainstate/references/extension_mechanisms.md +293 -0
  83. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
  84. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
  85. package/skills/brainstate/references/model-interop-and-migration.md +305 -0
  86. package/skills/brainstate/references/simulation-environment.md +117 -0
  87. package/skills/brainstate/references/size-inference-variations.md +279 -0
  88. package/skills/brainstate/references/state-graph-operations.md +216 -0
  89. package/skills/brainstate/references/state_collections_and_utilities.md +235 -0
  90. package/skills/brainstate/scripts/integrator_rnn.py +359 -0
  91. package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
  92. package/skills/brainstate/scripts/modern_cnn.py +73 -0
  93. package/skills/brainstate/scripts/resnet.py +130 -0
  94. package/skills/brainunit/SKILL.md +287 -0
  95. package/skills/brainunit/references/array-creation.md +158 -0
  96. package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
  97. package/skills/brainunit/references/array-mechanics.md +165 -0
  98. package/skills/brainunit/references/math-function-library.md +433 -0
  99. package/skills/brainunit/references/physical-constant-library.md +58 -0
  100. package/skills/brainunit/references/prefix-library.md +116 -0
  101. package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
  102. package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
  103. package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
  104. package/skills/brainx-general-guard/SKILL.md +153 -0
  105. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
  106. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
  107. package/skills/brainx-install/SKILL.md +2 -2
  108. package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
  109. /package/{bin → installation/bin}/brainx.js +0 -0
  110. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  111. /package/{lib → installation/lib}/bundle.js +0 -0
  112. /package/{lib → installation/lib}/cli.js +0 -0
  113. /package/{lib → installation/lib}/constants.js +0 -0
  114. /package/{lib → installation/lib}/hash.js +0 -0
  115. /package/{lib → installation/lib}/paths.js +0 -0
  116. /package/{lib → installation/lib}/prompts.js +0 -0
  117. /package/{lib → installation/lib}/receipt.js +0 -0
@@ -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`