brainx-skill 1.0.13 → 1.0.14

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 (44) hide show
  1. package/README.md +26 -0
  2. package/installation/lib/cli.js +16 -4
  3. package/installation/lib/literature-mcp.js +536 -0
  4. package/manifest.json +2 -0
  5. package/mcp-servers/codex/README.md +24 -4
  6. package/mcp-servers/codex/UPSTREAM.md +3 -1
  7. package/mcp-servers/codex/server.mjs +2 -0
  8. package/mcp-servers/codex/system-prompt.md +30 -19
  9. package/mcp-servers/codex/test/server.test.mjs +12 -1
  10. package/mcp-servers/fulltext-resolver/README.md +136 -0
  11. package/mcp-servers/fulltext-resolver/REUSE.md +32 -0
  12. package/mcp-servers/fulltext-resolver/THIRD_PARTY_NOTICES.md +57 -0
  13. package/mcp-servers/fulltext-resolver/server.mjs +128 -0
  14. package/mcp-servers/fulltext-resolver/src/document.mjs +253 -0
  15. package/mcp-servers/fulltext-resolver/src/http.mjs +173 -0
  16. package/mcp-servers/fulltext-resolver/src/identifiers.mjs +123 -0
  17. package/mcp-servers/fulltext-resolver/src/model.mjs +105 -0
  18. package/mcp-servers/fulltext-resolver/src/resolver.mjs +305 -0
  19. package/mcp-servers/fulltext-resolver/src/sources/biorxiv.mjs +135 -0
  20. package/mcp-servers/fulltext-resolver/src/sources/europe-pmc.mjs +132 -0
  21. package/mcp-servers/fulltext-resolver/src/sources/openalex.mjs +165 -0
  22. package/mcp-servers/fulltext-resolver/test/document.test.mjs +82 -0
  23. package/mcp-servers/fulltext-resolver/test/resolver.test.mjs +287 -0
  24. package/mcp-servers/fulltext-resolver/test/server.test.mjs +63 -0
  25. package/mcp-servers/fulltext-resolver/test/sources.test.mjs +229 -0
  26. package/package.json +10 -3
  27. package/skills/bio-neuro-lit/SKILL.md +206 -0
  28. package/skills/bio-neuro-lit/THIRD_PARTY_NOTICES.md +34 -0
  29. package/skills/bio-neuro-lit/agents/openai.yaml +4 -0
  30. package/skills/bio-neuro-lit/references/tool-contracts.md +73 -0
  31. package/skills/bio-neuro-lit/scripts/deepxiv_fetch.py +110 -0
  32. package/skills/bio-neuro-lit/scripts/exa_search.py +190 -0
  33. package/skills/brainx-general-guard/SKILL.md +17 -0
  34. package/skills/brainx-modeling-loop/SKILL.md +33 -20
  35. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +47 -7
  36. package/skills/brainx-visualization/SKILL.md +157 -0
  37. package/skills/brainx-visualization/agents/openai.yaml +4 -0
  38. package/skills/brainx-visualization/references/interactive-and-visualization-styling.md +155 -0
  39. package/skills/brainx-visualization/references/neural-data-visualization.md +141 -0
  40. package/skills/brainx-visualization/references/statistical-and-model-visualization.md +133 -0
  41. package/skills/package-skills/braincell/SKILL.md +16 -6
  42. package/skills/package-skills/braincell/references/braintools/input-current.md +200 -0
  43. package/skills/package-skills/braincell/references/braintools/metric.md +152 -0
  44. package/skills/package-skills/braincell/references/braintools/optimizer.md +179 -0
@@ -52,11 +52,13 @@ A `SingleCompartment` cell stores one membrane voltage per independent neuron an
52
52
  | `braincell.channel.*` | Use for membrane-current and gating dynamics; inspect `root_type` before attachment, and attach root-cell channels such as `IL` directly to the cell. |
53
53
  | `cell.init_state()` / `cell.reset_state()` | Use before the first step or to reseed an existing cell; they initialize or reset voltage, spike, ion, and channel State without changing the model declaration. |
54
54
  | `cell.update(I_ext)` | Use for one integration step; pass a current-density or total-current `Quantity`, let the cell area normalize total current, update all cellular State, and receive the spike output. |
55
+ | `braintools.input.Constant(...)` | Use when a current-clamp protocol contains timed baseline and stimulation sections; generate one unit-aware time-major sample per step under the rollout `dt`. |
55
56
  | `brainstate.environ.context()` / `brainstate.transform.for_loop()` | Use to provide `dt` and `t` and to execute a transformed time loop that returns recorded State instead of mutating Python containers. |
56
57
 
57
58
  ```python
58
59
  import braincell
59
60
  import brainstate
61
+ import braintools
60
62
  import brainunit as u
61
63
 
62
64
 
@@ -79,22 +81,27 @@ class HH(braincell.SingleCompartment):
79
81
 
80
82
  cell = HH(1)
81
83
  cell.init_state()
82
- current = 5.0 * u.uA / u.cm**2
83
84
 
84
85
 
85
- def step(t):
86
+ def step(t, current):
86
87
  with brainstate.environ.context(t=t):
87
88
  spike = cell.update(current)
88
89
  return cell.V.value, spike
89
90
 
90
91
 
91
92
  with brainstate.environ.context(dt=0.01 * u.ms):
93
+ protocol = braintools.input.Constant([
94
+ (0.0 * u.uA / u.cm**2, 20.0 * u.ms),
95
+ (5.0 * u.uA / u.cm**2, 60.0 * u.ms),
96
+ (0.0 * u.uA / u.cm**2, 20.0 * u.ms),
97
+ ])
98
+ current = protocol()
92
99
  times = u.math.arange(
93
100
  0.0 * u.ms,
94
- 100.0 * u.ms,
101
+ protocol.duration,
95
102
  brainstate.environ.get_dt(),
96
103
  )
97
- voltages, spikes = brainstate.transform.for_loop(step, times)
104
+ voltages, spikes = brainstate.transform.for_loop(step, times, current)
98
105
 
99
106
  assert voltages.shape[:1] == times.shape
100
107
  assert spikes.shape[:1] == times.shape
@@ -102,7 +109,7 @@ assert spikes.shape[:1] == times.shape
102
109
 
103
110
  Treat `V_th` only as the spike-event threshold; it does not change the membrane equation. Keep membrane capacitance and channel conductance density-based in the canonical path. `update()` accepts current density or total current and uses `SingleCompartment.area` to normalize total input; do not manually area-scale only part of the model. Use `size=N` for `N` independent cells, never for `N` compartments. For a multidimensional condition sweep, use the condition-grid shape as `size` and pass shape-aligned channel parameters and inputs; do not wrap identity functions in `vmap` merely to construct that grid.
104
111
 
105
- Open `references/area-scaled-hh-pattern.md` when changing cell geometry or explicitly converting density parameters to total quantities. Open `references/ion-library.md`, `references/channel-library.md`, or `references/mixions-for-adaptation.md` only when the classical fixed-ion HH path is insufficient.
112
+ Open `references/braintools/input-current.md` when generating timed sections, pulses, waveforms, or stochastic injected current. Open `references/area-scaled-hh-pattern.md` when changing cell geometry or explicitly converting density parameters to total quantities. Open `references/ion-library.md`, `references/channel-library.md`, or `references/mixions-for-adaptation.md` only when the classical fixed-ion HH path is insufficient.
106
113
 
107
114
  ## Build and run a multicompartment cell
108
115
 
@@ -175,8 +182,11 @@ Open only the smallest reference that owns the non-canonical decision.
175
182
  |---|---|
176
183
  | `references/area-scaled-hh-pattern.md` | Changing single-compartment geometry or converting density parameters consistently to total capacitance and conductance. |
177
184
  | `references/braincell-custom-ion-channel-authoring.md` | Implementing a custom ion or channel after confirming that no built-in mechanism fits. |
185
+ | `references/braintools/input-current.md` | Generating or composing unit-aware current sections, pulses, waveforms, or stochastic stimulation for a cellular rollout. |
186
+ | `references/braintools/metric.md` | Selecting standard waveform losses or neuroscience metrics for cellular fitting or trace evaluation; keep custom observation features separate. |
187
+ | `references/braintools/optimizer.md` | Selecting a gradient optimizer or a standalone SciPy or Nevergrad fitting boundary after the objective and reset lifecycle are fixed. |
178
188
  | `references/channel-library.md` | Selecting a built-in sodium, potassium, calcium, leak, HCN, or mixed-ion channel. |
179
- | `references/scripts/fitting_hh_neuron.py` | Studying the official complete HH fitting composition: custom sodium and potassium channels, trace loading, unit-bearing bounds, independent cell initialization, time-major rollout, voltage loss, candidate `vmap`, and Nevergrad. Supply the upstream trace CSVs and reconcile its source-version APIs with the current BrainCell and BrainState skills before adapting it. |
189
+ | `references/scripts/fitting_hh_neuron.py` | Studying the official complete HH fitting composition: custom sodium and potassium channels, trace loading, unit-bearing bounds, independent cell initialization, time-major rollout, voltage loss, candidate `vmap`, and Nevergrad. Also open the three local `references/braintools/` files before adapting it; supply the upstream trace CSVs and reconcile its source-version APIs with the current BrainCell and BrainState skills. |
180
190
  | `references/ion-library.md` | Choosing fixed, Nernst-initialized, or dynamic ions and their concentration behavior. |
181
191
  | `references/mixions-for-adaptation.md` | Adding calcium-dependent adaptation, AHP/KCa currents, rebound, dynamic calcium, or multi-ion channel dependencies. |
182
192
  | `references/multicompartment/multicompartment-cell-workflow.md` | Extending the canonical `Morphology -> Cell -> paint/place -> run` path and selecting the exclusive multicompartment references. |
@@ -0,0 +1,200 @@
1
+ # Braintools input currents
2
+
3
+ Use this reference to generate unit-aware stimulation currents, waveforms,
4
+ pulses, and stochastic processes. Prefer the composable class API when a
5
+ protocol combines, transforms, repeats, or sequences several signals; use the
6
+ functional API for one direct array.
7
+
8
+ ## Choose an interface
9
+
10
+ | Interface | Use when | Result |
11
+ |---|---|---|
12
+ | Composable classes | The protocol needs algebra, clipping, smoothing, time shifts, repetition, overlays, or concatenation | Returns an `Input` object; call it to generate the array. |
13
+ | Functional helpers | One signal can be generated in a single call | Returns the generated array immediately. |
14
+
15
+ Names ending in `Input` or `_input` are deprecated aliases. Use the class and
16
+ function names documented below.
17
+
18
+ ## Time-step and composition model
19
+
20
+ An `Input` stores a duration and reads its time step from
21
+ `brainstate.environ`. Calling it generates a cached array; pass
22
+ `recompute=True` when the stochastic or environmental inputs must be evaluated
23
+ again.
24
+
25
+ | API | Description |
26
+ |---|---|
27
+ | `Input(duration)` | Base class for composable currents. It exposes `duration`, `dt`, `n_steps`, and `shape`. |
28
+ | `input_obj(recompute=False)` | Generate and return the current array. |
29
+ | `input_obj.scale(factor)` | Multiply all values by a factor. |
30
+ | `input_obj.shift(time_shift)` | Delay or advance the signal in time. |
31
+ | `input_obj.clip(min_val, max_val)` | Bound the signal values. |
32
+ | `input_obj.smooth(tau)` | Apply exponential smoothing. |
33
+ | `input_obj.repeat(n_times)` | Repeat the pattern. |
34
+ | `input_obj.apply(func)` | Apply a custom transformation to the generated values. |
35
+ | `a + b`, `a - b`, `a * b`, `a / b`, `-a` | Combine compatible signals pointwise. |
36
+ | `a & b` | Concatenate signals sequentially in time. |
37
+ | `a \| b` | Overlay signals by taking their pointwise maximum. |
38
+
39
+ ```python
40
+ import brainstate
41
+ import brainunit as u
42
+ from braintools.input import Constant, Ramp, Sinusoidal
43
+
44
+ with brainstate.environ.context(dt=0.1 * u.ms):
45
+ baseline = Constant([(0.2 * u.nA, 500 * u.ms)])
46
+ ramp = Ramp(0 * u.nA, 1 * u.nA, 500 * u.ms)
47
+ oscillation = Sinusoidal(
48
+ amplitude=0.5 * u.nA,
49
+ frequency=10 * u.Hz,
50
+ duration=500 * u.ms,
51
+ )
52
+ protocol = (baseline + ramp + 0.5 * oscillation).clip(
53
+ 0 * u.nA,
54
+ 2 * u.nA,
55
+ )
56
+ current = protocol()
57
+ assert current.shape[0] == protocol.n_steps
58
+ ```
59
+
60
+ **Invariant:** set or scope `brainstate.environ.dt` before constructing and
61
+ generating the protocol. A different `dt` changes the number of samples.
62
+
63
+ ## Feed a protocol into a BrainCell rollout
64
+
65
+ A generated protocol is time-major data: construct it under the rollout `dt`,
66
+ then give it to `for_loop` so one current sample reaches each cell step.
67
+
68
+ | API | Description |
69
+ |---|---|
70
+ | `Constant([(value, duration), ...])` | Use for a baseline-pulse-baseline protocol; calling it under the active `dt` returns one unit-aware sample per step. |
71
+ | `brainstate.transform.for_loop(step, times, current)` | Slice `times` and `current` together along their leading axes and stack the step outputs. |
72
+
73
+ ```python
74
+ import braincell
75
+ import brainstate
76
+ import braintools
77
+ import brainunit as u
78
+
79
+
80
+ class PassiveCell(braincell.SingleCompartment):
81
+ def __init__(self, size):
82
+ super().__init__(size)
83
+ self.IL = braincell.channel.IL(
84
+ size,
85
+ E=-65.0 * u.mV,
86
+ g_max=0.03 * u.mS / u.cm**2,
87
+ )
88
+
89
+
90
+ with brainstate.environ.context(dt=0.1 * u.ms):
91
+ cell = PassiveCell(1)
92
+ cell.init_state()
93
+ protocol = braintools.input.Constant([
94
+ (0.0 * u.uA / u.cm**2, 20.0 * u.ms),
95
+ (5.0 * u.uA / u.cm**2, 60.0 * u.ms),
96
+ (0.0 * u.uA / u.cm**2, 20.0 * u.ms),
97
+ ])
98
+ current = protocol()
99
+ times = u.math.arange(
100
+ 0.0 * u.ms,
101
+ protocol.duration,
102
+ brainstate.environ.get_dt(),
103
+ )
104
+
105
+ def step(t, injected_current):
106
+ with brainstate.environ.context(t=t):
107
+ cell.update(injected_current)
108
+ return cell.V.value
109
+
110
+ voltages = brainstate.transform.for_loop(step, times, current)
111
+
112
+ assert voltages.shape == (1000, 1)
113
+ ```
114
+
115
+ Do not reconstruct the same sections with comparisons against `t` inside
116
+ `step`. For a mapped parameter sweep that shares this protocol, keep the
117
+ per-step current sample unmapped (`in_axes=None`) while mapping the independent
118
+ condition parameters and dynamical State. Open
119
+ `skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md` for
120
+ the mapped-State contract.
121
+
122
+ ## Basic currents
123
+
124
+ | Composable API | Functional API | Use |
125
+ |---|---|---|
126
+ | `Section(values, durations)` | `section(values, durations, return_length=False)` | Build consecutive constant sections from parallel value and duration sequences. |
127
+ | `Constant(I_and_duration)` | `constant(I_and_duration)` | Build piecewise-constant sections from `(value, duration)` pairs. |
128
+ | `Step(amplitudes, step_times, duration=None)` | `step(amplitudes, step_times, duration=None)` | Change among discrete levels at specified times. |
129
+ | `Ramp(c_start, c_end, duration, t_start=None, t_end=None)` | `ramp(c_start, c_end, duration, t_start=None, t_end=None)` | Interpolate linearly, optionally only within a subinterval. |
130
+
131
+ `Constant` takes a sequence of pairs:
132
+
133
+ ```python
134
+ from braintools.input import Constant
135
+
136
+ protocol = Constant([
137
+ (0.0 * u.nA, 100 * u.ms),
138
+ (1.0 * u.nA, 200 * u.ms),
139
+ (0.0 * u.nA, 100 * u.ms),
140
+ ])
141
+ ```
142
+
143
+ Use `Section(values=[...], durations=[...])` when separate arrays are more
144
+ convenient.
145
+
146
+ ## Pulse generators
147
+
148
+ | Composable API | Functional API | Use |
149
+ |---|---|---|
150
+ | `Spike(sp_times, duration, sp_lens=..., sp_sizes=...)` | `spike(sp_times, sp_lens, sp_sizes, duration)` | Place short current spikes at explicit times. |
151
+ | `GaussianPulse(amplitude, center, sigma, duration)` | `gaussian_pulse(amplitude, center, sigma, duration, ...)` | Generate a Gaussian-shaped pulse. |
152
+ | `ExponentialDecay(amplitude, tau, duration, ...)` | `exponential_decay(amplitude, tau, duration, ...)` | Generate a one-sided exponential decay. |
153
+ | `DoubleExponential(amplitude, tau_rise, tau_decay, ...)` | `double_exponential(amplitude, tau_rise, tau_decay, ...)` | Generate a rise-and-decay synaptic-current shape. |
154
+ | `Burst(...)` | `burst(...)` | Generate repeated pulses within one or more bursts. |
155
+
156
+ ## Waveforms
157
+
158
+ | Composable API | Functional API | Use |
159
+ |---|---|---|
160
+ | `Sinusoidal(amplitude, frequency, duration, ...)` | `sinusoidal(amplitude, frequency, duration, ...)` | Generate a fixed-frequency sine wave. |
161
+ | `Square(amplitude, frequency, duration, ...)` | `square(amplitude, frequency, duration, ...)` | Generate a square wave; configure its duty cycle deliberately. |
162
+ | `Triangular(amplitude, frequency, duration, ...)` | `triangular(amplitude, frequency, duration, ...)` | Generate a triangular periodic wave. |
163
+ | `Sawtooth(amplitude, frequency, duration, ...)` | `sawtooth(amplitude, frequency, duration, ...)` | Generate a sawtooth periodic wave. |
164
+ | `Chirp(amplitude, f_start, f_end, duration, ...)` | `chirp(amplitude, f_start, f_end, duration, ...)` | Sweep frequency over time. |
165
+ | `NoisySinusoidal(amplitude, frequency, ..., noise_amplitude=...)` | `noisy_sinusoidal(amplitude, frequency, ..., noise_amplitude=...)` | Add stochastic noise to a sinusoid. |
166
+
167
+ ## Stochastic processes
168
+
169
+ | Composable API | Functional API | Use |
170
+ |---|---|---|
171
+ | `WienerProcess(duration, n=1, t_start=None, t_end=None, sigma=1.0, seed=None)` | `wiener_process(duration, sigma=1.0, n=1, ...)` | Model Brownian fluctuations with independent Gaussian increments. |
172
+ | `OUProcess(mean, sigma, tau, duration, n=1, t_start=None, t_end=None, seed=None)` | `ou_process(mean, sigma, tau, duration, n=1, ...)` | Model mean-reverting fluctuations around `mean`. |
173
+ | `Poisson(rate, duration, n=1, t_start=None, t_end=None, amplitude=1.0, seed=None)` | `poisson(rate, duration, amplitude=1.0, n=1, ...)` | Generate independent Poisson spike-current trains. |
174
+
175
+ Use `seed=` for reproducibility and `n=` for multiple independent processes.
176
+ For Poisson input, ensure `rate * dt` is a valid per-bin spike probability.
177
+ Call with `recompute=True` only when a new stochastic realization is intended.
178
+
179
+ ## Composition wrappers
180
+
181
+ These classes are normally created through operators or methods rather than
182
+ instantiated directly.
183
+
184
+ | API | Description |
185
+ |---|---|
186
+ | `Composite(input1, input2, operator)` | Pointwise combination of two inputs. |
187
+ | `ConstantValue(value, duration)` | Promote a scalar to a duration-matched input. |
188
+ | `Sequential(*inputs)` | Time concatenation corresponding to `&`. |
189
+ | `TimeShifted(input_obj, time_shift)` | Result of `.shift()`. |
190
+ | `Clipped(input_obj, min_val=None, max_val=None)` | Result of `.clip()`. |
191
+ | `Smoothed(input_obj, tau)` | Result of `.smooth()`. |
192
+ | `Repeated(input_obj, n_times)` | Result of `.repeat()`. |
193
+ | `Transformed(input_obj, func)` | Result of `.apply()`. |
194
+
195
+ Pointwise operands must have compatible duration, shape, and units. Use `&`
196
+ when durations differ and should occur one after another.
197
+
198
+ ## Official source
199
+
200
+ - `https://brainx.chaobrain.com/braintools/apis/input.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`
@@ -0,0 +1,179 @@
1
+ # Braintools optimizer selection
2
+
3
+ Use this reference after the BrainCell objective, rollout, State reset, and gradient target are correct. Select an optimizer interface and learning-rate policy without changing the simulation graph or confusing gradient-step optimizers with standalone search wrappers.
4
+
5
+ ## Choose a gradient optimizer
6
+
7
+ Choose the optimizer family by training regime and resource constraint. Ordinary reverse-mode optimizers register the selected `ParamState` tree once and accept the matching gradient tree through `update(grads)`.
8
+
9
+ ### General minibatch optimizers
10
+
11
+ Use these optimizers for ordinary repeated gradient steps; establish `Adam` or `SGD` as the baseline before selecting a specialized update rule.
12
+
13
+ | API | Description |
14
+ |---|---|
15
+ | `SGD(...)` | Use for stochastic gradient descent with optional momentum and weight decay when a simple non-adaptive baseline is required. |
16
+ | `Momentum(...)` | Use for momentum updates without selecting the broader `SGD` interface. |
17
+ | `MomentumNesterov(...)` | Use when the optimization method requires Nesterov-accelerated momentum. |
18
+ | `Adam(...)` | Use as the canonical adaptive default after validating finite, nonzero gradients. |
19
+ | `AdamW(...)` | Use when the training policy requires decoupled weight decay; set `weight_decay` deliberately. |
20
+ | `Adagrad(...)` | Use when per-parameter learning rates should accumulate squared-gradient history. |
21
+ | `Adadelta(...)` | Use when the Adadelta extension of Adagrad is explicitly required. |
22
+ | `RMSprop(...)` | Use when the method should scale updates by a moving average of squared gradients. |
23
+ | `Adamax(...)` | Use when the infinity-norm Adam variant is required. |
24
+ | `Nadam(...)` | Use when combining Adam with Nesterov acceleration. |
25
+ | `RAdam(...)` | Use when rectifying adaptive learning-rate variance addresses observed early-step instability. |
26
+ | `Yogi(...)` | Use when the Yogi additive second-moment update is part of the intended method. |
27
+ | `Rprop(...)` | Use when resilient backpropagation should adapt per-parameter step sizes from gradient signs. |
28
+ | `AdaBelief(...)` | Use when adapting step size from the optimizer's belief in the gradient direction is required. |
29
+ | `Lion(...)` | Use when a sign-momentum optimizer is chosen to reduce optimizer-State memory. |
30
+ | `Novograd(...)` | Use when layer-wise gradient normalization with momentum is required. |
31
+ | `Fromage(...)` | Use only when the Free-scale Optimal Method for Adaptive Gradient method is explicitly selected. |
32
+
33
+ ### Large-scale and memory-efficient optimizers
34
+
35
+ Use these optimizers only when large-batch scaling or optimizer-State memory is an explicit constraint.
36
+
37
+ | API | Description |
38
+ |---|---|
39
+ | `Lamb(...)` | Use for layer-wise adaptive moments in an explicitly large-batch training regime. |
40
+ | `Lars(...)` | Use for layer-wise adaptive rate scaling in an explicitly large-batch training regime. |
41
+ | `Adafactor(...)` | Use when factorized second-moment estimates are needed to reduce optimizer-State memory. |
42
+ | `SM3(...)` | Use for memory-efficient adaptive updates in a large or sparse model. |
43
+
44
+ ### Wrapper and full-batch optimizers
45
+
46
+ Use these variants when the update requires an optimizer composition or a smooth full-batch objective rather than an ordinary standalone minibatch rule.
47
+
48
+ | API | Description |
49
+ |---|---|
50
+ | `Lookahead(...)` | Use when wrapping an inner Optax gradient transformation with periodic slow-weight interpolation. |
51
+ | `LBFGS(...)` | Use for a small, smooth, full-batch problem suited to limited-memory quasi-Newton updates; verify its step contract before replacing a minibatch optimizer. |
52
+
53
+ ### Custom Optax transformations
54
+
55
+ Use the bridge when no named Braintools optimizer expresses the required Optax transformation.
56
+
57
+ | API | Description |
58
+ |---|---|
59
+ | `OptaxOptimizer(tx=..., lr=...)` | Use when supplying a custom Optax transformation while preserving Braintools parameter registration, optimizer State, gradient clipping, weight decay, and scheduler integration. |
60
+
61
+ Do not switch optimizer, scheduler, surrogate, and temporal reduction simultaneously. Establish an `Adam` loss and gradient baseline, then vary one optimization decision.
62
+
63
+ ## Gradient-step lifecycle
64
+
65
+ Every ordinary gradient optimizer owns persistent optimizer State and mutates exactly the registered trainable State:
66
+
67
+ | API | Use and result |
68
+ |---|---|
69
+ | `model.states(brainstate.ParamState)` | Select trainable model State; dynamical voltage, conductance, spike, and delay State remain outside the optimizer. |
70
+ | `optimizer.register_trainable_weights(params)` | Register the parameter tree and initialize optimizer State. |
71
+ | `brainstate.transform.grad(loss_fn, params, return_value=True)` | Produce a gradient tree matching `params` and the scalar loss. |
72
+ | `optimizer.update(grads)` | Apply one update to the registered parameters. |
73
+
74
+ ```python
75
+ params = net.states(brainstate.ParamState)
76
+ optimizer = braintools.optim.Adam(lr=3e-3)
77
+ optimizer.register_trainable_weights(params)
78
+
79
+ @brainstate.transform.jit
80
+ def train_step():
81
+ brainstate.nn.init_all_states(net, batch_size=batch_size)
82
+ grads, loss = brainstate.transform.grad(
83
+ loss_fn,
84
+ params,
85
+ return_value=True,
86
+ )()
87
+ optimizer.update(grads)
88
+ return loss
89
+ ```
90
+
91
+ Register the same tree passed to `grad`. Do not rebuild or re-register that tree inside every compiled step.
92
+
93
+ Use `braintools.optim.UniqueStateManager(...)` only when an arbitrary nested PyTree may contain repeated references to the same `State`; it deduplicates State identity before optimization. An ordinary `model.states(brainstate.ParamState)` collection already expresses the canonical model-owned target.
94
+
95
+ ## Learning-rate schedulers
96
+
97
+ Pass an `LRScheduler` instance as `lr=` to any gradient-based `OptaxOptimizer`. A float is treated as a constant learning rate.
98
+
99
+ | API | Description |
100
+ |---|---|
101
+ | `LRScheduler(...)` | Subclass when implementing a custom schedule; it defines attachment, stepping, current-rate access, and State serialization. |
102
+ | `StepLR(...)` | Use for staircase decay by `gamma` every `step_size` scheduler steps. |
103
+ | `MultiStepLR(...)` | Use for multiplicative decay at explicitly chosen milestones. |
104
+ | `ConstantLR(...)` | Use to multiply the base learning rate by a constant factor for a configured interval. |
105
+ | `LinearLR(...)` | Use to scale the learning rate linearly between configured factors. |
106
+ | `ExponentialLR(...)` | Use for smooth multiplicative decay by `gamma` at every scheduler step. |
107
+ | `PolynomialLR(...)` | Use when the learning rate must follow a polynomial decay. |
108
+ | `ExponentialDecayLR(...)` | Use for exponential decay with explicit step-based control. |
109
+ | `CosineAnnealingLR(...)` | Use for smooth cosine annealing from the base rate toward `eta_min`; match `T_max` to the scheduler-call cadence. |
110
+ | `CosineAnnealingWarmRestarts(...)` | Use for cosine annealing that periodically restarts its cycle. |
111
+ | `WarmupCosineSchedule(...)` | Use when one schedule must warm up first and then anneal by cosine. |
112
+ | `CyclicLR(...)` | Use to oscillate the learning rate between configured bounds. |
113
+ | `OneCycleLR(...)` | Use for a single super-convergence cycle; derive `total_steps` from the actual number of scheduler calls. |
114
+ | `ReduceLROnPlateau(...)` | Use when a validation metric should trigger decay after stalled improvement; call `step(metric=...)`. |
115
+ | `WarmupScheduler(...)` | Use to increase the learning rate linearly during a warmup phase. |
116
+ | `PiecewiseConstantSchedule(...)` | Use for step-wise transitions among explicitly configured constant rates. |
117
+ | `ChainedScheduler(...)` | Use to apply multiple scheduler transformations together. |
118
+ | `SequentialLR(...)` | Use to switch among schedulers at configured epoch milestones. |
119
+
120
+ ```python
121
+ scheduler = braintools.optim.StepLR(
122
+ base_lr=3e-3,
123
+ step_size=20,
124
+ gamma=0.5,
125
+ )
126
+ optimizer = braintools.optim.Adam(lr=scheduler)
127
+ optimizer.register_trainable_weights(params)
128
+
129
+ # After each epoch, outside the neural time-step transform:
130
+ optimizer.lr.step()
131
+ current_lr = optimizer.lr.get_last_lr()
132
+ ```
133
+
134
+ For validation-driven scheduling, use the different call contract:
135
+
136
+ ```python
137
+ scheduler = braintools.optim.ReduceLROnPlateau(
138
+ base_lr=3e-3,
139
+ mode="min",
140
+ factor=0.5,
141
+ patience=5,
142
+ )
143
+ optimizer = braintools.optim.Adam(lr=scheduler)
144
+
145
+ # After validation:
146
+ scheduler.step(metric=float(validation_loss))
147
+ ```
148
+
149
+ Count scheduler calls explicitly. Stepping an epoch-configured schedule once per batch silently changes its effective timescale.
150
+
151
+ ## Standalone and forward-mode optimizers
152
+
153
+ These interfaces own more of the optimization operation than `update(grads)`:
154
+
155
+ | API | Description |
156
+ |---|---|
157
+ | `ScipyOptimizer(loss_fun, bounds, method=...)` | Use for a smooth bounded or constrained objective solved as one optimization problem; match sequence bounds to `loss_fun(*params)` or dict bounds to `loss_fun(**params)`, then call `minimize(n_iter=...)` to obtain a SciPy result whose `x` matches the bounds structure. |
158
+ | `NevergradOptimizer(batched_loss_fun, bounds, n_sample, ...)` | Use when gradients are unavailable or unreliable; accept candidate-stacked parameters, return one loss per candidate, and call `minimize(n_iter=...)` to obtain the best parameter structure. |
159
+ | `SOFO(model, loss_fn, ...)` | Use for a feed-forward model when sampled forward-mode second-order directions are required; register its `ParamState`s, then call `step(inputs, targets)` to compute and apply the direction and return the pre-update loss. |
160
+ | `SOFOScan(rnn_cell, loss_fn, ...)` | Use for a stateful one-step recurrent cell with `(latent, inputs) -> (new_latent, output)`; `step(inputs, targets)` propagates forward-mode tangents through the sequence and applies one update. |
161
+
162
+ `ScipyOptimizer` and `NevergradOptimizer` deliberately raise for the State-based register/update methods. Do not place either inside the canonical compiled minibatch train step.
163
+
164
+ When SciPy bounds carry BrainUnit quantities, the wrapper optimizes numeric mantissas and calls `loss_fun` without units; reconstruct any required physical quantities inside the objective. Nevergrad reattaches units to returned parameters when the corresponding bounds carry units. Apply either optimizer's returned parameters to model State explicitly.
165
+
166
+ For Nevergrad, total objective evaluations are approximately `n_iter * n_sample`. `budget=` configures Nevergrad's internal strategy but does not cap that outer evaluation count.
167
+
168
+ ## Routing and official sources
169
+
170
+ Open `metric.md` for loss and reduction choice and `input-current.md` for generated current-clamp protocols. Open `../scripts/fitting_hh_neuron.py` for the complete BrainCell candidate-evaluation and Nevergrad composition; reconcile its source-version APIs with the BrainCell root skill before adapting it.
171
+
172
+ Official sources:
173
+
174
+ - `https://brainx.chaobrain.com/braintools/apis/optim.html`
175
+ - `https://brainx.chaobrain.com/braintools/optim/01_nevergrad_optimizer.html`
176
+ - `https://brainx.chaobrain.com/braintools/optim/02_scipy_optimizer.html`
177
+ - `https://brainx.chaobrain.com/braintools/optim/03_optax_getting_started.html`
178
+ - `https://brainx.chaobrain.com/braintools/optim/04_learning_rate_scheduling.html`
179
+ - `https://brainx.chaobrain.com/braintools/optim/05_advanced_optimizers.html`