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.
Files changed (120) hide show
  1. package/README.md +10 -8
  2. package/adapters/gemini.js +7 -0
  3. package/adapters/opencode.js +7 -0
  4. package/adapters/windsurf.js +7 -0
  5. package/installation/lib/installer.js +4 -1
  6. package/manifest.json +6 -1
  7. package/package.json +8 -2
  8. package/skills/braincell/SKILL.md +182 -0
  9. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  10. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +273 -0
  11. package/skills/braincell/references/channel-library.md +85 -0
  12. package/skills/braincell/references/ion-library.md +87 -0
  13. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  14. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  15. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  16. package/skills/braincell/references/multicompartment/filter-function-library.md +154 -0
  17. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  18. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  19. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  20. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +260 -0
  21. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  22. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  23. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  24. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  25. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  26. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  27. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  28. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  29. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  30. package/skills/brainevent/SKILL.md +268 -0
  31. package/skills/brainevent/references/connectivity-variants.md +312 -0
  32. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  33. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  34. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  35. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  36. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  37. package/skills/brainevent/references/sparse-formats.md +182 -0
  38. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  39. package/skills/brainmass/SKILL.md +290 -0
  40. package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
  41. package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
  42. package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  43. package/skills/brainmass/references/braintools/cogtask.md +190 -0
  44. package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
  45. package/skills/brainmass/references/braintools/metric.md +157 -0
  46. package/skills/brainmass/references/braintools/optimizer.md +187 -0
  47. package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
  48. package/skills/brainmass/references/braintools/surrogate.md +151 -0
  49. package/skills/brainmass/references/coupling-network-api.md +148 -0
  50. package/skills/brainmass/references/datasets-api.md +72 -0
  51. package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
  52. package/skills/brainmass/references/forward-observation-api.md +131 -0
  53. package/skills/brainmass/references/horn-task-training.md +199 -0
  54. package/skills/brainmass/references/modellibrary.md +104 -0
  55. package/skills/brainmass/references/noiseprocesses.md +121 -0
  56. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
  57. package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
  58. package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
  59. package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
  60. package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
  61. package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
  62. package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
  63. package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
  64. package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
  65. package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
  66. package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
  67. package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
  68. package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
  69. package/skills/brainmass/references/visualization-analysis-api.md +130 -0
  70. package/skills/brainpy-state/SKILL.md +232 -0
  71. package/skills/brainpy-state/references/array-creation.md +158 -0
  72. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  73. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  75. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  76. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  77. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  78. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  79. package/skills/brainpy-state/references/component-selection.md +273 -0
  80. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  81. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  82. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  83. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  84. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  85. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  86. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  87. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  88. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  89. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  90. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  91. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  92. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  93. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  94. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  95. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  96. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  97. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  98. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  99. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  100. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  101. package/skills/brainstate/SKILL.md +1 -1
  102. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
  103. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
  104. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
  105. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
  106. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
  107. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
  108. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
  109. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
  110. package/skills/brainstate/references/collective_model_operations.md +9 -9
  111. package/skills/brainstate/references/extension_mechanisms.md +12 -1
  112. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
  113. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
  114. package/skills/brainstate/references/model-interop-and-migration.md +11 -1
  115. package/skills/brainstate/references/size-inference-variations.md +11 -0
  116. package/skills/brainstate/references/state-graph-operations.md +13 -15
  117. package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
  118. package/skills/brainx-general-guard/SKILL.md +68 -0
  119. package/skills/brainstate/references/braintools-optimizer-reference.md +0 -133
  120. package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
@@ -0,0 +1,171 @@
1
+ # BrainState parameter transforms and regularizers catalog
2
+
3
+ Use this reference only from
4
+ `references/brainstate/parameter-constraints-regularization.md`, after that
5
+ parent has established the operational `nn.Param` workflow. It is the exhaustive
6
+ selection catalog for `brainstate.nn` parameter transforms and regularizers.
7
+ Return to the parent for `ParamState` versus `nn.Param`, `nn.Const`, forward
8
+ computation, optimizer targeting, and loss integration.
9
+
10
+ These are parameter-value transforms, not execution transforms such as `brainstate.transform.jit`, `grad`, or `vmap`.
11
+
12
+ ## Transform contract
13
+
14
+ `nn.Transform` defines `forward()`, `inverse()`, and optional `log_abs_det_jacobian()` operations between stored and model-space values. `nn.Param` initializes its storage with `t.inverse(value)`, returns `t.forward(param.val)` from `param.value()`, and applies `t.inverse(value)` in `param.set_value()`.
15
+
16
+ The official API describes the family as bijective parameter transformations. The implementation also includes projection-like transforms such as `ClipT`, `ReluT`, and `UnitVectorT` whose forward operations are not one-to-one. Prefer a smooth bijection when unconstrained optimization and reversible change-of-variables semantics matter.
17
+
18
+ Official sources:
19
+
20
+ - https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
21
+ - https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Transform.html
22
+ - https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_transform.py
23
+
24
+ ## Transform selection by target domain
25
+
26
+ The call forms below come from the current official `_transform.py` constructors. Check the installed-version generated class page before depending on a signature across BrainState releases.
27
+
28
+ ### Identity, rescaling, and reparameterization
29
+
30
+ | Need | Class and current call form | Selection distinction |
31
+ |---|---|---|
32
+ | No constraint | `IdentityT()` | Default transform; stored and model values coincide. |
33
+ | Linear scale and shift | `AffineT(scale, shift)` | Applies a reversible affine reparameterization. |
34
+ | Box-Cox-style power map | `PowerT(lmbda=0.5)` | Select for the documented power transformation rather than a domain guarantee. |
35
+
36
+ ### Positive, negative, and half-line values
37
+
38
+ | Need | Class and current call form | Selection distinction |
39
+ |---|---|---|
40
+ | Smooth value above a lower bound | `SoftplusT(lower)` | Maps the real line to `(lower, infinity)` with a softplus forward map. |
41
+ | Smooth value below an upper bound | `NegSoftplusT(upper)` | Maps the real line to `(-infinity, upper)` with a negative-softplus forward map. |
42
+ | Exponential value above a lower bound | `ExpT(lower)` | Maps the real line to `(lower, infinity)` with an exponential forward map. |
43
+ | Logarithmic forward reparameterization | `LogT(lower)` | `forward(x)` maps `(lower, infinity)` to the real line; its direction differs from `ExpT`. |
44
+ | ReLU lower bound | `ReluT(lower_bound=0.0)` | Projection-like lower bound; negative inputs collapse and the map is not one-to-one. |
45
+ | Strictly positive value | `PositiveT()` | Maps model values to `(0, infinity)`. |
46
+ | Strictly negative value | `NegativeT()` | Maps model values to `(-infinity, 0)`. |
47
+
48
+ `SoftplusT(lower)` is the canonical smooth positive-domain choice. Do not replace it with `ReluT` or clipping when the workflow needs gradients through a reversible unconstrained parameterization.
49
+
50
+ ### Bounded values
51
+
52
+ | Need | Class and current call form | Selection distinction |
53
+ |---|---|---|
54
+ | Smooth open interval | `SigmoidT(lower, upper)` | Maps the real line to `(lower, upper)` and approaches, but does not cross, either bound. |
55
+ | Tanh-based open interval | `TanhT(lower, upper)` | Uses tanh for a bounded range. |
56
+ | Softsign-based open interval | `SoftsignT(lower, upper)` | Uses softsign for a bounded range. |
57
+ | Adjustable sigmoid sharpness | `ScaledSigmoidT(lower, upper, beta=1.0)` | Adds a `beta` sharpness/temperature control to the bounded sigmoid map. |
58
+ | Hard bounded projection | `ClipT(lower, upper)` | Clips in both `forward()` and `inverse()`; it is not a smooth bijection at or beyond the bounds. |
59
+
60
+ ### Structured and composite values
61
+
62
+ | Need | Class and current call form | Selection distinction |
63
+ |---|---|---|
64
+ | Monotonically increasing entries | `OrderedT()` | Produces ordered output values. |
65
+ | Probability simplex | `SimplexT()` | Stick-breaking map to non-negative entries summing to one. An unconstrained final axis of length `n` produces a simplex axis of length `n + 1`. |
66
+ | Unit L2 norm | `UnitVectorT()` | Normalizes the input vector; the forward map is projection-like and its inverse returns the supplied value. |
67
+ | Sequential composition | `ChainT(*transforms)` | Applies transforms left to right in the supplied order and inverses in reverse order. |
68
+ | Selective transformation | `MaskedT(mask, transform, safe_value=1.0)` | Applies one transform only at Boolean-mask positions. |
69
+
70
+ Use the documented composition order:
71
+
72
+ ```python
73
+ chained = nn.ChainT(
74
+ nn.AffineT(scale=2.0, shift=1.0),
75
+ nn.SoftplusT(lower=0.0),
76
+ )
77
+ value = chained.forward(jnp.array(0.0))
78
+ ```
79
+
80
+ `AffineT` runs first and `SoftplusT` runs second.
81
+
82
+ Official sources:
83
+
84
+ - https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
85
+ - https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
86
+ - https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
87
+ - https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_transform.py
88
+
89
+ ## Regularization contract
90
+
91
+ `nn.Regularization` defines three operations:
92
+
93
+ - `loss(value)` returns the scalar penalty added to an objective.
94
+ - `sample_init(shape)` samples an initial value from the implied prior.
95
+ - `reset_value()` returns the value used by `nn.Param.reset_to_prior()`.
96
+
97
+ `nn.Param.reg_loss()` returns zero for a fixed parameter or a parameter without `reg=`; otherwise it evaluates `reg.loss(param.value())`. Attaching `reg=` never adds the result to the training objective automatically.
98
+
99
+ `nn.ChainedReg(*regularizations, weight=1.0, fit_hyper=False)` sums its component losses and multiplies the result by the overall weight. Its `sample_init()` and `reset_value()` use the first component.
100
+
101
+ Official sources:
102
+
103
+ - https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
104
+ - https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.Regularization.html
105
+ - https://brainx.chaobrain.com/brainstate/apis/generated/brainstate.nn.ChainedReg.html
106
+ - https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_regularization.py
107
+
108
+ ## Classical and structural regularizer selection
109
+
110
+ | Modeling intent | Official API |
111
+ |---|---|
112
+ | Abstract regularization contract | `Regularization` |
113
+ | L1/Lasso sparsity | `L1Reg` |
114
+ | L2/Ridge shrinkage | `L2Reg` |
115
+ | Combined L1 and L2 | `ElasticNetReg` |
116
+ | Robust penalty | `HuberReg` |
117
+ | Group sparsity | `GroupLassoReg` |
118
+ | Total variation or local smoothness | `TotalVariationReg` |
119
+ | Soft maximum-norm pressure | `MaxNormReg` |
120
+ | Entropy pressure | `EntropyReg` |
121
+ | Orthogonal structure | `OrthogonalReg` |
122
+ | Spectral-norm structure | `SpectralNormReg` |
123
+ | Several penalties on one value | `ChainedReg` |
124
+
125
+ Use the generated class page for exact axes, reduction behavior, weights, and initialization arguments; these differ by regularizer and should not be inferred from neighboring classes.
126
+
127
+ Official source: https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
128
+
129
+ ## Prior-distribution regularizer selection
130
+
131
+ Prior regularizers encode distributional assumptions for Bayesian-inspired parameter estimation. Match both the scientific assumption and the prior's support. A regularizer contributes a preference through the loss; attach a transform separately when the parameter must remain in that support by construction.
132
+
133
+ | Parameter assumption | Official API |
134
+ |---|---|
135
+ | Gaussian prior | `GaussianReg` |
136
+ | Student's t prior | `StudentTReg` |
137
+ | Cauchy prior | `CauchyReg` |
138
+ | Bounded uniform prior | `UniformReg` |
139
+ | Value in `[0, 1]` under a Beta prior | `BetaReg` |
140
+ | Positive value under a log-normal prior | `LogNormalReg` |
141
+ | Positive value under an exponential prior | `ExponentialReg` |
142
+ | Positive value under a Gamma prior | `GammaReg` |
143
+ | Variance under an inverse-Gamma prior | `InverseGammaReg` |
144
+ | Scale-invariant log-uniform/Jeffreys prior | `LogUniformReg` |
145
+ | Strong sparsity with heavy tails | `HorseshoeReg` |
146
+ | Variable selection | `SpikeAndSlabReg` |
147
+ | Probability simplex | `DirichletReg` |
148
+
149
+ Official source: https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
150
+
151
+ ## Interaction safeguards
152
+
153
+ - Keep transform direction explicit: `nn.Param.value()` calls `forward()`, while initialization and `set_value()` call `inverse()`.
154
+ - Do not treat `LogT` and `ExpT` as interchangeable; their documented forward directions are opposite.
155
+ - Do not treat a projection-like transform as a smooth bijective change of variables.
156
+ - Do not assume `SimplexT` preserves the final-axis length.
157
+ - Apply `ChainT` in listed order and invert it in reverse order.
158
+ - Use `MaskedT` for Boolean-mask selection instead of hand-rolling selective transformation.
159
+ - Current source makes transformed-value caching explicit: `param.cache()` populates it, writes invalidate it, and `param.value()` otherwise recomputes without populating it.
160
+ - `reset_to_prior()` uses `reg.reset_value()`; use `reg.sample_init(shape)` separately when a random prior draw is required.
161
+ - Return to `parameter-constraints-regularization.md` for objective integration and complete workflow code.
162
+
163
+ ## Mirror source urls
164
+
165
+ - https://brainx.chaobrain.com/brainstate/apis/nn/parameters.html
166
+ - https://brainx.chaobrain.com/brainstate/apis/nn/regularization.html
167
+ - https://brainx.chaobrain.com/brainstate/tutorials/core/05_parameters_transforms_regularization.html
168
+ - https://brainx.chaobrain.com/brainstate/how_to/constrain_and_regularize_parameters.html
169
+ - https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_param.py
170
+ - https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_transform.py
171
+ - https://github.com/chaobrain/brainstate/blob/main/brainstate/nn/_regularization.py
@@ -0,0 +1,190 @@
1
+ # Braintools cognitive tasks
2
+
3
+ Use this reference to choose a pre-built cognitive paradigm or construct a
4
+ phase-based task that generates time-major training trials. It covers task
5
+ composition, features, value encoders, labels, variable-duration trials, and
6
+ sampling contracts.
7
+
8
+ For BrainMass, use these trials with the direct HORN minibatch workflow in
9
+ `references/horn-task-training.md`; do not send task batches through `Fitter`.
10
+
11
+ ## Choose the task path
12
+
13
+ | Decision | Use | Important constraint |
14
+ |---|---|---|
15
+ | Standard paradigm | Instantiate a pre-built `Task` subclass | Override parameters, not its phase machinery, unless the paradigm itself changes. |
16
+ | One-off custom task | Construct `Task(phases=..., input_features=..., output_features=..., trial_init=...)` | Put all trial-specific random values in `trial_init`. |
17
+ | Reusable task family | Subclass `Task` and implement `define_features()`, `define_phases()`, and `trial_init()` | Keep feature definitions and phase construction deterministic. |
18
+ | Categorical target | Keep `output_mode='categorical'` and write `outputs={'label': ...}` | Targets have shape `(T,)` per trial. |
19
+ | Continuous or multi-channel target | Set `output_mode='vector'` and write output features by name | Targets have shape `(T, num_outputs)` per trial. |
20
+ | Variable-duration trial | Use `VariableDuration`, `If`, `Switch`, or `While` | Request `return_mask=True` and size computation with `max_trial_duration()`. |
21
+
22
+ ## Core task framework
23
+
24
+ `Task` executes a phase tree against one mutable trial-level `Context`, then
25
+ exposes deterministic indexed sampling and vectorized batch sampling.
26
+
27
+ | API | Description |
28
+ |---|---|
29
+ | `Task(phases=None, input_features=None, output_features=None, trial_init=None, name=None, output_mode='categorical', seed=None, num_classes=None, dt=None, **kwargs)` | Use as the dataset-like task owner. It binds the phase tree, feature layout, output mode, seed, and time step. |
30
+ | `Context` | Use as the shared per-trial state. It carries RNG state, input/output buffers, timing, phase history, and values written by `trial_init`. |
31
+ | `Task.sample_trial(index=0, key=None)` | Use when metadata and the uncompiled trial path are needed; it returns `(X, Y, info)`. |
32
+ | `Task.sample(index)` / `task[index]` | Use for one JIT-compiled trial; it returns `(X, Y)`. |
33
+ | `Task.batch_sample(size, time_first=True, return_meta=False, start_index=0, return_mask=False)` | Use for training batches. It folds the trial index into the task seed and returns time-major arrays by default. |
34
+ | `Task.max_trial_duration(ctx=None)` | Use to obtain the static timestep upper bound for variable-length buffers. |
35
+ | `Task.get_trial_meta()` | Override when `batch_sample(..., return_meta=True)` should return task-specific metadata. |
36
+
37
+ ```python
38
+ import brainunit as u
39
+ from braintools.cogtask import (
40
+ Delay,
41
+ Feature,
42
+ Fixation,
43
+ Response,
44
+ Stimulus,
45
+ Task,
46
+ circular,
47
+ concat,
48
+ label,
49
+ )
50
+
51
+ fixation = Feature(1, "fixation")
52
+ stimulus = Feature(8, "stimulus")
53
+ choice = Feature(2, "choice")
54
+
55
+ task = Task(
56
+ phases=concat([
57
+ Fixation(100 * u.ms, inputs={"fixation": 1.0}),
58
+ Stimulus(
59
+ 500 * u.ms,
60
+ inputs={"stimulus": circular("direction")},
61
+ ),
62
+ Delay(500 * u.ms, inputs={"fixation": 1.0}),
63
+ Response(
64
+ 100 * u.ms,
65
+ outputs={"label": label("ground_truth")},
66
+ ),
67
+ ]),
68
+ input_features=fixation + stimulus,
69
+ output_features=fixation + choice,
70
+ trial_init=lambda ctx: ctx.update(
71
+ ground_truth=ctx.rng.choice(2),
72
+ direction=ctx.rng.uniform(0.0, 2.0 * 3.14159),
73
+ ),
74
+ seed=0,
75
+ )
76
+
77
+ X, Y = task.batch_sample(32)
78
+ assert X.shape[1] == 32
79
+ assert Y.shape[:2] == X.shape[:2]
80
+ ```
81
+
82
+ **Invariant:** wrap a context-key label with `label("key")`. A bare string is
83
+ treated as a literal value and fails instead of reading from `Context`.
84
+
85
+ ## Phases and composition
86
+
87
+ Phases own one trial epoch. Declarative phases fill named feature slices from
88
+ constants or callables with the contract `f(ctx, feature) -> array`.
89
+
90
+ | API | Description |
91
+ |---|---|
92
+ | `Phase` | Subclass only when declarative input/output dictionaries cannot express the epoch. |
93
+ | `DeclarativePhase(duration, inputs=None, outputs=None, noise=None, on_enter=None, on_exit=None, name=None)` | Use for custom named epochs. Input values may be scalar, `(feature.num,)`, or `(duration, feature.num)`. |
94
+ | `Fixation(...)`, `Stimulus(...)`, `Delay(...)`, `Response(...)`, `Cue(...)`, `Blank(...)` | Use these semantic names for ordinary epochs; they share the declarative interface. |
95
+ | `Sample(...)`, `Test(...)`, `Recall(...)`, `Match(...)`, `Comparison(...)` | Use these semantic names for working-memory epochs. |
96
+ | `Sequence(...)` / `a >> b` | Execute phases sequentially. |
97
+ | `Repeat(...)` / `a * n` | Repeat one phase or compound phase a fixed number of times. |
98
+ | `Parallel(...)` / `a \| b` | Execute phase contributions over the same interval. |
99
+ | `concat(phases)` | Build a sequence from a list. |
100
+ | `If(condition, then, else_=None, name='If')` | Select one of two branches from trial state. Packed mode uses `jax.lax.cond`. |
101
+ | `Switch(...)` | Dispatch among several phase branches. The packed selector must return a Python-hashable key, not a tracer. |
102
+ | `While(...)` | Repeat while a condition is true, bounded by `max_iterations`. The packed condition must return a Python `bool`. |
103
+ | `VariableDuration(min_duration, max_duration, ctx_key, ...)` | Reserve `max_duration` but use the per-trial duration in `ctx[ctx_key]`; `min_duration` and `max_duration` must have matching units. |
104
+
105
+ Conditional choices must be derivable from `trial_init` or an earlier phase
106
+ hook. Keep tensor outputs authoritative in compiled code; phase-history metadata
107
+ is best effort when branches are traced.
108
+
109
+ ## Features, encoders, and labels
110
+
111
+ `FeatureSet` concatenates fixed-width logical channels into one flat vector and
112
+ assigns each feature a slice through `.i`.
113
+
114
+ | API | Description |
115
+ |---|---|
116
+ | `Feature(num, name=None)` | Define one fixed-width input or output channel. |
117
+ | `FeatureSet` | Collect features and manage their shifted slices. |
118
+ | `CircleFeature` | Define an angular or directional feature with a value range. |
119
+ | `feature_a + feature_b` / `feature_a \| feature_b` | Concatenate copied features without mutating the operands. |
120
+ | `one_hot(...)` | Encode a discrete class as a one-hot feature value. |
121
+ | `identity(...)` | Pass a context value through directly. |
122
+ | `circular(...)` | Encode a direction with cosine tuning. |
123
+ | `von_mises(...)` | Encode a direction with a circular-normal population profile. |
124
+ | `cos_sin(...)` | Encode a direction index as repeated cosine/sine pairs. |
125
+ | `scalar(...)` | Broadcast one scalar across a feature. |
126
+ | `gaussian(...)` | Encode a scalar with a Gaussian bump. |
127
+ | `ctx_value(...)` | Read a dynamic value directly from `Context`. |
128
+ | `label(value)` | Produce a categorical label specification from a literal, callable, or context key. |
129
+ | `match_label(...)` | Produce match/non-match target codes. |
130
+ | `comparison_label(...)` | Produce comparison target codes. |
131
+
132
+ Noise values in a declarative phase map feature names to sigma quantities in
133
+ `ms**0.5`. The runtime samples noise per phase and scales it by
134
+ `1 / sqrt(dt)` so variance is stable when `dt` changes.
135
+
136
+ ## Pre-built tasks
137
+
138
+ Use the paradigm whose trial semantics match the experiment.
139
+
140
+ | Family | API | Purpose |
141
+ |---|---|---|
142
+ | Decision making | `PerceptualDecisionMaking(...)` | Perceptual decision making with motion coherence. |
143
+ | Decision making | `PerceptualDecisionMakingDelayResponse(...)` | Perceptual decision making with a response delay. |
144
+ | Decision making | `ContextDecisionMaking(...)` | Context-dependent multimodal decisions. |
145
+ | Decision making | `SingleContextDecisionMaking(...)` | A single-context decision task. |
146
+ | Decision making | `PulseDecisionMaking(...)` | Decisions from discrete evidence pulses. |
147
+ | Working memory | `DelayMatchSample(...)` | Delayed match-to-sample. |
148
+ | Working memory | `DualDelayMatchSample(...)` | Dual delayed match-to-sample. |
149
+ | Working memory | `DelayComparison(...)` | Compare values across a delay. |
150
+ | Working memory | `DelayMatchCategory(...)` | Match stimulus category across a delay. |
151
+ | Working memory | `DelayPairedAssociation(...)` | Delayed paired association. |
152
+ | Working memory | `GoNoGo(...)` | Go/no-go response selection. |
153
+ | Working memory | `IntervalDiscrimination(...)` | Compare or classify time intervals. |
154
+ | Working memory | `PostDecisionWager(...)` | Decision confidence with a wager option. |
155
+ | Working memory | `ReadySetGo(...)` | Timing reproduction from ready/set cues. |
156
+ | Working memory | `DelayDirectionReproduction(...)` | Reproduce a direction after a delay. |
157
+ | Working memory | `ImmediateDirectionReproduction(...)` | Reproduce a direction without a memory delay. |
158
+ | Working memory | `DelayDirectionClassification(...)` | Classify direction after a delay. |
159
+ | Working memory | `ImmediateDirectionClassification(...)` | Classify direction immediately. |
160
+ | Reasoning | `HierarchicalReasoning(...)` | Integrate hierarchical cues or rules. |
161
+ | Reasoning | `ProbabilisticReasoning(...)` | Make decisions under probabilistic evidence. |
162
+ | Motor | `AntiReach(...)` | Produce an anti-reach or anti-saccade response. |
163
+ | Motor | `Reaching1D(...)` | Produce a one-dimensional reaching output. |
164
+ | Motor | `EvidenceAccumulation(...)` | Produce a motor response from accumulated evidence. |
165
+
166
+ ## Sampling, masks, and reproducibility
167
+
168
+ For one fixed-length trial, `X` has shape `(T, num_inputs)` and categorical `Y`
169
+ has shape `(T,)`. `batch_sample(B)` returns `(T, B, ...)` unless
170
+ `time_first=False`.
171
+
172
+ For a variable-length task:
173
+
174
+ - `max_trial_duration()` returns a Python `int` suitable for a static buffer
175
+ dimension.
176
+ - `batch_sample(..., return_mask=True)` returns a Boolean mask in the same
177
+ time/batch layout as `X` and `Y`.
178
+ - Trailing buffer positions stay zero and have a false mask.
179
+ - Every traced `step_count(ctx)` must satisfy
180
+ `0 <= step_count(ctx) <= max_steps(ctx)`.
181
+
182
+ A task constructed with `seed=N` derives trial `i` with
183
+ `jax.random.fold_in(PRNGKey(N), i)`. Reusing the same index is deterministic;
184
+ advance `start_index` between batches to avoid overlapping trials. An explicit
185
+ `dt=` overrides the environment; otherwise the task reads
186
+ `brainstate.environ.get_dt()`.
187
+
188
+ ## Official source
189
+
190
+ - `https://brainx.chaobrain.com/braintools/apis/cogtask.html`
@@ -0,0 +1,83 @@
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
+ For BrainMass, open this reference only when a custom training workflow must
9
+ encode experimental or task inputs before they enter the model. Ordinary HORN
10
+ feature sequences and `Fitter` targets do not require spike encoding.
11
+
12
+ ## Choose an encoder
13
+
14
+ Choose the representation from the information the downstream model must
15
+ preserve.
16
+
17
+ | Encoder family | Use when | Important result |
18
+ |---|---|---|
19
+ | Latency | Magnitude should control time to first spike | Larger normalized values spike earlier. |
20
+ | Rate or Poisson | Magnitude should control spike frequency | Returns a time-major spike train whose empirical rate represents the input. |
21
+ | Population | A scalar should activate overlapping receptive fields | Expands each scalar across a neuron population. |
22
+ | Bernoulli | Each time bin should be sampled independently | Converts normalized values into per-bin spike probabilities. |
23
+ | Delta | Only meaningful temporal changes should emit spikes | Detects threshold-crossing differences between successive samples. |
24
+ | Step current | A spiking neuron should receive an analog current level | Returns current values rather than a binary spike code. |
25
+ | Spike count | The window must contain an exact input-dependent count | Places a bounded number of spikes randomly or regularly. |
26
+ | Temporal | A discrete value should select a precise timing pattern | Maps values to synchronized temporal templates. |
27
+ | Rank order | Relative feature ordering matters more than absolute scale | Emits higher-ranked features before lower-ranked features. |
28
+
29
+ ## Spike encoders
30
+
31
+ All encoder objects are reusable callables. Pass the input as the first argument
32
+ and the number of encoded timesteps as `n_time=`.
33
+
34
+ | API | Description |
35
+ |---|---|
36
+ | `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. |
37
+ | `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. |
38
+ | `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. |
39
+ | `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. |
40
+ | `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. |
41
+ | `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. |
42
+ | `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. |
43
+ | `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`. |
44
+ | `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. |
45
+ | `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. |
46
+
47
+ ```python
48
+ import jax.numpy as jnp
49
+ from braintools import LatencyEncoder
50
+
51
+ values = jnp.array([0.02, 0.5, 1.0])
52
+ encoder = LatencyEncoder(method="linear", normalize=True)
53
+ spikes = encoder(values, n_time=5)
54
+
55
+ assert spikes.shape == (5, 3)
56
+ assert jnp.argmax(spikes[:, 2]) < jnp.argmax(spikes[:, 1])
57
+ assert jnp.argmax(spikes[:, 1]) < jnp.argmax(spikes[:, 0])
58
+ ```
59
+
60
+ **Invariant:** treat the leading axis as encoded time. Validate normalization,
61
+ time-window length, and stochastic variability before comparing encoders.
62
+
63
+ ## Spike operations
64
+
65
+ Use these element-wise operations only on boolean or binary-compatible spike
66
+ tensors with broadcast-compatible shapes.
67
+
68
+ | API | Description |
69
+ |---|---|
70
+ | `spike_bitwise_or(x, y)` | Return binary OR, implemented as `x + y - x * y`. |
71
+ | `spike_bitwise_and(x, y)` | Return binary AND, implemented as element-wise multiplication. |
72
+ | `spike_bitwise_iand(x, y)` | Return inverse AND, documented as `(NOT x) AND y`. |
73
+ | `spike_bitwise_not(x)` | Invert a binary spike tensor. |
74
+ | `spike_bitwise_xor(x, y)` | Return XOR between two spike tensors. |
75
+ | `spike_bitwise_ixor(x, y)` | Apply the documented inverse-XOR operation. |
76
+ | `spike_bitwise(x, y, op)` | Dispatch by `op` over `'or'`, `'and'`, `'iand'`, `'xor'`, and `'ixor'`. |
77
+
78
+ Do not use these helpers as fuzzy arithmetic on rates or arbitrary continuous
79
+ arrays; their formulas assume binary values.
80
+
81
+ ## Official source
82
+
83
+ - `https://brainx.chaobrain.com/braintools/apis/braintools.html`
@@ -0,0 +1,157 @@
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
+ For BrainMass, prefer `brainmass.objectives` for standard `Fitter` time-series,
9
+ FC, and FCD comparisons. Use this reference for HORN supervised losses,
10
+ held-out metrics, or a custom fitting statistic not owned by
11
+ `brainmass.objectives`.
12
+
13
+ ## Choose a metric family
14
+
15
+ | Task | Use | Important constraint |
16
+ |---|---|---|
17
+ | Independent binary or multilabel classification | Sigmoid binary cross entropy or focal loss | Logits and labels must have broadcast-compatible class structure. |
18
+ | Mutually exclusive classes | Softmax cross entropy | Choose one-hot/probability labels or the integer-label variant explicitly. |
19
+ | Continuous fitting | Squared, absolute, Huber, log-cosh, or cosine losses | Set `reduction` rather than assuming a scalar result. |
20
+ | Spike timing | Victor-Purpura or van Rossum distance | Inputs are spike-time trains, not dense spike matrices. |
21
+ | Population spiking | Firing-rate and synchrony metrics | Dense spike matrices are time-major unless the API says otherwise. |
22
+ | LFP spectrum or coupling | PSD, coherence, PAC, CSD, entropy, or phase coherence | Pass the sample interval as `dt`, not sampling frequency as `fs`. |
23
+ | Functional connectivity | Correlation and connectivity functions | Time series use `(num_time, num_signals)`. |
24
+
25
+ ## Classification losses
26
+
27
+ | API | Description |
28
+ |---|---|
29
+ | `sigmoid_binary_cross_entropy(logits, labels)` | Use for independent binary classes; returns element-wise sigmoid cross entropy. |
30
+ | `softmax_cross_entropy(logits, labels)` | Use for mutually exclusive classes represented by one-hot or probability labels. |
31
+ | `softmax_cross_entropy_with_integer_labels(logits, labels)` | Use the more direct integer-index form for mutually exclusive classes. Validate every label yourself. |
32
+ | `hinge_loss(...)` | Use for binary margin classification. |
33
+ | `perceptron_loss(...)` | Use for the binary perceptron objective. |
34
+ | `multiclass_hinge_loss(...)` | Use for a multiclass margin objective. |
35
+ | `multiclass_perceptron_loss(...)` | Use for a multiclass perceptron objective. |
36
+ | `poly_loss_cross_entropy(...)` | Use when the specified method requires PolyLoss cross entropy. |
37
+ | `kl_divergence(...)` | Compare probability distributions. |
38
+ | `kl_divergence_with_log_targets(...)` | Use when predictions and targets are already in log space. |
39
+ | `convex_kl_divergence(...)` | Use when the convex KL variant is required. |
40
+ | `ctc_loss(...)` | Use for sequence alignment without frame-level labels. |
41
+ | `ctc_loss_with_forward_probs(...)` | Use when the CTC forward probabilities are also needed. |
42
+ | `sigmoid_focal_loss(...)` | Use for class imbalance among independent binary targets. |
43
+ | `nll_loss(...)` | Use with log-probability classification outputs. |
44
+
45
+ ```python
46
+ import jax.numpy as jnp
47
+ from braintools.metric import (
48
+ softmax_cross_entropy_with_integer_labels,
49
+ )
50
+
51
+ logits = jnp.array([
52
+ [2.0, 1.0, 0.1],
53
+ [0.5, 2.5, 0.3],
54
+ ])
55
+ labels = jnp.array([0, 1])
56
+
57
+ per_example = softmax_cross_entropy_with_integer_labels(logits, labels)
58
+ loss = jnp.mean(per_example)
59
+ assert loss.ndim == 0
60
+ ```
61
+
62
+ **Critical exception:** JAX gather silently clamps out-of-range integer labels
63
+ in `softmax_cross_entropy_with_integer_labels`. Validate
64
+ `0 <= labels < logits.shape[-1]`; the function does not raise for invalid
65
+ labels.
66
+
67
+ ## Regression and pairwise metrics
68
+
69
+ | API | Description |
70
+ |---|---|
71
+ | `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. |
72
+ | `absolute_error(...)` | Use for element-wise absolute error. |
73
+ | `l1_loss(...)` | Use for mean absolute-error behavior according to its axis/reduction options. |
74
+ | `l2_loss(...)` | Use for squared L2 loss. |
75
+ | `l2_norm(...)` | Return the L2 norm of prediction error. |
76
+ | `safe_norm(...)` | Use when a differentiable lower bound must prevent an unstable zero norm. |
77
+ | `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. |
78
+ | `log_cosh(...)` | Use for a smooth robust regression loss. |
79
+ | `cosine_similarity(...)` | Compare vector direction. |
80
+ | `cosine_distance(...)` | Return the corresponding cosine distance. |
81
+ | `pairwise_cosine_similarity(X, Y, ...)` | Return all pairwise cosine similarities between sample sets. |
82
+ | `pairwise_cosine_distance(X, Y, ...)` | Return all pairwise cosine distances between sample sets. |
83
+
84
+ Do not conflate element-wise loss with final optimization reduction. Preserve
85
+ batch and time axes until the scientific loss definition determines how to
86
+ reduce them.
87
+
88
+ ## Correlation and functional connectivity
89
+
90
+ | API | Description |
91
+ |---|---|
92
+ | `cross_correlation(spikes, bin, dt)` | Calculate a cross-correlation synchrony index from a time-major spike matrix. |
93
+ | `voltage_fluctuation(voltages)` | Estimate synchrony from population voltage variance. |
94
+ | `matrix_correlation(a, b)` | Correlate upper-triangular entries of two square matrices. |
95
+ | `weighted_correlation(x, y, weights)` | Compute weighted Pearson correlation for two one-dimensional series. |
96
+ | `functional_connectivity(activities)` | Return the pairwise Pearson correlation matrix for `(num_time, num_signals)` data; NaNs are replaced with zero. |
97
+ | `functional_connectivity_dynamics(activities, window_size, step_size)` | Compare sliding-window connectivity matrices to produce functional-connectivity dynamics. |
98
+
99
+ ## Spike-train metrics
100
+
101
+ | API | Description |
102
+ |---|---|
103
+ | `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. |
104
+ | `firing_rate(spikes, width, dt=None)` | Average across neurons and smooth population rate with a rectangular window of physical width. |
105
+ | `victor_purpura_distance(spike_times_1, spike_times_2, cost_factor=1.0)` | Measure edit cost from insertions, deletions, and temporal shifts. |
106
+ | `van_rossum_distance(spike_times_1, spike_times_2, tau=...)` | Compare exponentially filtered spike trains. |
107
+ | `spike_train_synchrony(spikes, window_size, dt=None)` | Compute SPIKE-style synchronization on a population matrix. |
108
+ | `burst_synchrony_index(spikes, dt=None, ...)` | Measure co-occurring burst events. |
109
+ | `phase_locking_value(spikes, reference_freq, dt=None, ...)` | Measure spike phase locking to a reference oscillation. |
110
+ | `spike_time_tiling_coefficient(spikes, dt=None, tau=...)` | Compute STTC within a temporal tolerance. |
111
+ | `correlation_index(spikes, window_size, dt=None)` | Compute a windowed spike-train correlation index. |
112
+
113
+ ```python
114
+ import brainunit as u
115
+ from braintools.metric import firing_rate, spike_train_synchrony
116
+
117
+ # Shape: (num_time, num_neurons)
118
+ rate = firing_rate(spikes, width=10 * u.ms, dt=1 * u.ms)
119
+ synchrony = spike_train_synchrony(
120
+ spikes,
121
+ window_size=5 * u.ms,
122
+ dt=1 * u.ms,
123
+ )
124
+ ```
125
+
126
+ Keep dense spike matrices and lists of spike times distinct. Distance metrics
127
+ consume event times; population rate and synchrony metrics consume matrices.
128
+
129
+ ## Local field potential analysis
130
+
131
+ | API | Description |
132
+ |---|---|
133
+ | `unitary_LFP(times, spikes, neuron_type, seed=None, ...)` | Construct unitary LFP contributions from spikes; use the documented `'exc'` or `'inh'` neuron type. |
134
+ | `power_spectral_density(lfp, dt, nperseg=None, noverlap=None, freq_range=None)` | Return one-sided Welch frequencies and PSD. |
135
+ | `coherence_analysis(signal1, signal2, dt, ...)` | Return frequency-resolved magnitude-squared coherence. |
136
+ | `phase_amplitude_coupling(lfp, dt, phase_freq_range, amplitude_freq_range, ...)` | Return Tort modulation index plus phase-bin details. |
137
+ | `theta_gamma_coupling(lfp, dt, ...)` | Return theta-gamma coupling using standard bands. |
138
+ | `current_source_density(lfp, electrode_spacing, axis=0, ...)` | Estimate laminar CSD along the electrode axis. |
139
+ | `spectral_entropy(lfp, dt, ...)` | Return normalized spectral entropy. |
140
+ | `lfp_phase_coherence(lfp, dt, freq_band, ...)` | Compute pairwise phase coherence across channels. |
141
+
142
+ `power_spectral_density(..., freq_range=...)` uses boolean-mask indexing and
143
+ therefore has a data-dependent output length; that path is not JIT-compatible.
144
+ Compute the full spectrum inside JIT and filter outside when compilation is
145
+ required.
146
+
147
+ ## Structured, ranking, and smoothing losses
148
+
149
+ | API | Description |
150
+ |---|---|
151
+ | `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)->()`. |
152
+ | `ranking_softmax_loss(scores, labels, ...)` | Use for list-wise learning-to-rank objectives. |
153
+ | `smooth_labels(labels, alpha=...)` | Apply label smoothing to one-hot targets. |
154
+
155
+ ## Official source
156
+
157
+ - `https://brainx.chaobrain.com/braintools/apis/metric.html`