brainx-skill 1.0.2 → 1.0.6

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 (52) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +24 -56
  3. package/{lib → installation/lib}/installer.js +4 -4
  4. package/manifest.json +3 -1
  5. package/package.json +19 -9
  6. package/skills/brainstate/SKILL.md +399 -0
  7. package/skills/brainstate/agents/openai.yaml +4 -0
  8. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +483 -0
  9. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +176 -0
  10. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +199 -0
  11. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +166 -0
  12. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +210 -0
  13. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +450 -0
  14. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +157 -0
  15. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +286 -0
  16. package/skills/brainstate/references/braintools-optimizer-reference.md +133 -0
  17. package/skills/brainstate/references/collective_model_operations.md +195 -0
  18. package/skills/brainstate/references/extension_mechanisms.md +282 -0
  19. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -0
  20. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +217 -0
  21. package/skills/brainstate/references/libraries/solver-library-with-effects.md +85 -0
  22. package/skills/brainstate/references/model-interop-and-migration.md +295 -0
  23. package/skills/brainstate/references/simulation-environment.md +117 -0
  24. package/skills/brainstate/references/size-inference-variations.md +268 -0
  25. package/skills/brainstate/references/state-graph-operations.md +218 -0
  26. package/skills/brainstate/references/state_collections_and_utilities.md +224 -0
  27. package/skills/brainstate/scripts/integrator_rnn.py +359 -0
  28. package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
  29. package/skills/brainstate/scripts/modern_cnn.py +73 -0
  30. package/skills/brainstate/scripts/resnet.py +130 -0
  31. package/skills/brainunit/SKILL.md +287 -0
  32. package/skills/brainunit/references/array-creation.md +158 -0
  33. package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
  34. package/skills/brainunit/references/array-mechanics.md +165 -0
  35. package/skills/brainunit/references/math-function-library.md +433 -0
  36. package/skills/brainunit/references/physical-constant-library.md +58 -0
  37. package/skills/brainunit/references/prefix-library.md +116 -0
  38. package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
  39. package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
  40. package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
  41. package/skills/brainx-install/SKILL.md +21 -13
  42. package/skills/brainx-install/references/compatibility-and-release-matching.md +12 -10
  43. package/skills/brainx-install/references/uninstall-and-cleanup.md +186 -0
  44. /package/{bin → installation/bin}/brainx.js +0 -0
  45. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  46. /package/{lib → installation/lib}/bundle.js +0 -0
  47. /package/{lib → installation/lib}/cli.js +0 -0
  48. /package/{lib → installation/lib}/constants.js +0 -0
  49. /package/{lib → installation/lib}/hash.js +0 -0
  50. /package/{lib → installation/lib}/paths.js +0 -0
  51. /package/{lib → installation/lib}/prompts.js +0 -0
  52. /package/{lib → installation/lib}/receipt.js +0 -0
@@ -0,0 +1,165 @@
1
+ # Array mechanics
2
+
3
+ Use this reference for array metadata, indexing, functional updates, shape and axis transformations, joins and splits, repetition, named-axis transformations, and backend conversion of an existing `Quantity`.
4
+
5
+ ## Contents
6
+
7
+ - [Metadata and identity](#metadata-and-identity)
8
+ - [Indexing and functional updates](#indexing-and-functional-updates)
9
+ - [Quantity methods](#quantity-methods)
10
+ - [Functional structural API](#functional-structural-api)
11
+ - [Named-axis transformations](#named-axis-transformations)
12
+ - [Backend conversion](#backend-conversion)
13
+ - [Source-backed gotchas](#source-backed-gotchas)
14
+
15
+ ## Metadata and identity
16
+
17
+ | Property | Official meaning |
18
+ |---|---|
19
+ | `q.shape` | Shape of the mantissa array |
20
+ | `q.dtype` | Data type of the mantissa |
21
+ | `q.backend` | One of `'numpy'`, `'jax'`, `'cupy'`, `'torch'`, `'dask'`, or `'ndonnx'` |
22
+ | `q.itemsize` | Bytes in one mantissa element |
23
+ | `q.nbytes` | Total bytes consumed by the mantissa array |
24
+ | `q.strides` | Byte steps in each dimension, mirroring `numpy.ndarray.strides` |
25
+ | `q.flat` | 1-D iterator over mantissa elements with units preserved |
26
+ | `q.mT` | Transpose of the final two dimensions; requires at least 2-D |
27
+
28
+ Use `u.math.ndim(x)`, `u.math.shape(x)`, and `u.math.size(x)` when a functional query is preferable to a property lookup.
29
+
30
+ ## Indexing and functional updates
31
+
32
+ Ordinary indexing preserves the unit. `q.at` provides a functionally pure update interface:
33
+
34
+ ```python
35
+ import brainunit as u
36
+ import jax.numpy as jnp
37
+
38
+ x = jnp.arange(5.0) * u.mV
39
+ y = x.at[2].add(10 * u.mV)
40
+ # Expected: [0, 1, 12, 3, 4] mV; x remains unchanged.
41
+ selected = x.at[2].get()
42
+ # Expected: 2 mV.
43
+ ```
44
+
45
+ The documented update mappings are:
46
+
47
+ | Functional form | In-place equivalent |
48
+ |---|---|
49
+ | `x = x.at[idx].set(y)` | `x[idx] = y` |
50
+ | `x = x.at[idx].add(y)` | `x[idx] += y` |
51
+ | `x = x.at[idx].multiply(y)` | `x[idx] *= y` |
52
+ | `x = x.at[idx].divide(y)` | `x[idx] /= y` |
53
+ | `x = x.at[idx].power(y)` | `x[idx] **= y` |
54
+ | `x = x.at[idx].min(y)` | `x[idx] = minimum(x[idx], y)` |
55
+ | `x = x.at[idx].max(y)` | `x[idx] = maximum(x[idx], y)` |
56
+ | `x = x.at[idx].apply(ufunc)` | `ufunc.at(x, idx)` |
57
+ | `x.at[idx].get()` | `x[idx]` |
58
+
59
+ None of these expressions modifies the original object; each returns a modified copy. Inside `jit()`, assignments such as `x = x.at[idx].set(y)` are documented as being applied in place.
60
+
61
+ ## Quantity methods
62
+
63
+ | Exact signature | One-line description | Example & result |
64
+ |---|---|---|
65
+ | `reshape(shape, order='C')` | Return a quantity with the same data but a new shape. | `q = u.Quantity(jnp.array([1.0, 2.0, 3.0]), unit=u.mV); q.reshape((3, 1)).shape`<br>`# (3, 1)` |
66
+ | `flatten()` | Return a 1-D copy of this quantity. | `q = u.Quantity(jnp.array([[1.0, 2.0], [3.0, 4.0]]), unit=u.mV); q.flatten()`<br>`# Quantity([1. 2. 3. 4.], "mV")` |
67
+ | `squeeze(axis=None)` | Remove length-one axes from the array. | `q = u.Quantity(jnp.array([[[1.0]]]), unit=u.mV); q.squeeze().shape`<br>`# ()` |
68
+ | `expand_dims(axis)` | Insert new axes at the given positions. | `q = u.Quantity(jnp.array([1.0, 2.0]), unit=u.mV); q.expand_dims(0).shape`<br>`# (1, 2)` |
69
+ | `unsqueeze(axis)` | Insert a length-one axis (PyTorch-style alias for `expand_dims()`). | `q = u.Quantity(jnp.array([1.0, 2.0]), unit=u.mV); q.unsqueeze(0).shape`<br>`# (1, 2)` |
70
+ | `transpose(*axes)` | Return the array with axes transposed. | `q = u.Quantity(jnp.array([[1.0, 2.0], [3.0, 4.0]]), unit=u.mV); q.transpose().shape`<br>`# (2, 2)` |
71
+ | `swapaxes(axis1, axis2)` | Interchange two axes of the array. | `q = u.Quantity(jnp.array([[1.0, 2.0], [3.0, 4.0]]), unit=u.mV); q.swapaxes(0, 1).shape`<br>`# (2, 2)` |
72
+ | `repeat(repeats, axis=None)` | Repeat elements of the array. | `q = u.Quantity(jnp.array([1.0, 2.0]), unit=u.mV); q.repeat(2)`<br>`# Quantity([1. 1. 2. 2.], "mV")` |
73
+ | `tile(reps)` | Construct an array by repeating this quantity. | `q = u.Quantity(jnp.array([1.0, 2.0]), unit=u.mV); q.tile(2)`<br>`# Quantity([1. 2. 1. 2.], "mV")` |
74
+ | `split(indices_or_sections, axis=0)` | Split the array into multiple sub-arrays. | `q = u.Quantity(jnp.array([1.0, 2.0, 3.0]), unit=u.mV); parts = q.split(3); len(parts)`<br>`# 3` |
75
+ | `take(indices, axis=None, mode=None, unique_indices=False, indices_are_sorted=False, fill_value=None)` | Select elements from the array at the given indices. | `q = u.Quantity(jnp.array([10.0, 20.0, 30.0]), unit=u.mV); q.take(jnp.array([0, 2]))`<br>`# Quantity([10. 30.], "mV")` |
76
+ | `sort(axis=-1, stable=True, order=None)` | Sort the array in-place along the given axis. | `q = u.Quantity(jnp.array([3.0, 1.0, 2.0]), unit=u.mV); q.sort()`<br>`# Quantity([1. 2. 3.], "mV")` |
77
+ | `diagonal(offset=0, axis1=0, axis2=1)` | Return specified diagonals, preserving units. | `q = u.Quantity(jnp.array([[1.0, 2.0], [3.0, 4.0]]), unit=u.mV); q.diagonal()`<br>`# Quantity([1. 4.], "mV")` |
78
+ | `trace(offset=0, axis1=0, axis2=1)` | Sum along diagonals of the array, preserving units. | `q = u.Quantity(jnp.eye(3), unit=u.mV); q.trace()`<br>`# Quantity(3., "mV")` |
79
+ | `astype(dtype)` | Return a copy of this quantity with the mantissa cast to `dtype`. | `q = u.Quantity(jnp.array([1.0, 2.0]), unit=u.mV); q.astype(jnp.float64).dtype`<br>`# float64` |
80
+
81
+ ## Functional structural API
82
+
83
+ Use these `brainunit.math` functions when composing transformations without binding the operation to a method:
84
+
85
+ | Family | Exact APIs |
86
+ |---|---|
87
+ | Join | `concatenate(arrays, axis=0, dtype=None, **kwargs)`, `stack(arrays, axis=0, dtype=None, **kwargs)`, `block(arrays, **kwargs)`, `append(arr, values, axis=None, **kwargs)` |
88
+ | Stack variants | `row_stack`, `vstack`, `hstack`, `dstack`, `column_stack` |
89
+ | Split | `split`, `array_split`, `dsplit`, `hsplit`, `vsplit` |
90
+ | Minimum rank | `atleast_1d`, `atleast_2d`, `atleast_3d` |
91
+ | Broadcast | `broadcast_arrays(*args, **kwargs)`, `broadcast_to(array, shape, **kwargs)` |
92
+ | Shape | `reshape`, `moveaxis`, `transpose`, `swapaxes`, `expand_dims`, `squeeze`, `flatten`, `unflatten` |
93
+ | Repetition | `tile(A, reps, **kwargs)`, `repeat(a, repeats, axis=None, total_repeat_length=None, **kwargs)` |
94
+ | Selection | `take`, `gather`, `choose`, `compress`, `extract` |
95
+
96
+ The module API categorizes these as functions that keep units. Open the [complete functional structural API reference](array-mechanics/functional-structural-api.md) for every exact signature, official one-line description, and example with its result.
97
+
98
+ ```python
99
+ a = [1, 2] * u.second
100
+ b = [3, 4] * u.second
101
+ joined = u.math.concatenate([a, b])
102
+ # Expected: [1, 2, 3, 4] s.
103
+ rows = u.math.stack([a, b])
104
+ # Expected: [[1, 2], [3, 4]] s with shape (2, 2).
105
+ parts = u.math.array_split(joined, 2)
106
+ # Expected: two Quantity arrays, [1, 2] s and [3, 4] s.
107
+ ```
108
+
109
+ ## Named-axis transformations
110
+
111
+ `einrearrange(x, pattern, **axes_lengths)` covers transpose, reshape, squeeze, unsqueeze, stack, and concatenate. Composition uses C-order enumeration.
112
+
113
+ ```python
114
+ channels_last = u.math.einrearrange(x, 'b c h w -> b h w c')
115
+ # Expected: for shape-compatible x, axes change from (b, c, h, w) to (b, h, w, c); unit preserved.
116
+ flat = u.math.einrearrange(x, 'b h w c -> (b h w c)')
117
+ # Expected: for shape-compatible x, a one-dimensional Quantity with all elements; unit preserved.
118
+ split_batch = u.math.einrearrange(
119
+ x,
120
+ '(b1 b2) h w c -> b1 b2 h w c',
121
+ b1=2,
122
+ )
123
+ # Expected: for shape-compatible x, the batch axis splits into axes 2 and b/2; unit preserved.
124
+ ```
125
+
126
+ `einrepeat(x, pattern, **axes_lengths)` covers repeat, tile, and broadcast-like patterns:
127
+
128
+ ```python
129
+ expanded = u.math.einrepeat(x, 'h w c -> h new_axis w c', new_axis=5)
130
+ # Expected: for shape-compatible x, a new length-5 axis is inserted after h; unit preserved.
131
+ tiled = u.math.einrepeat(x, 'h w c -> (2 h) (2 w) c')
132
+ # Expected: for shape-compatible x, h and w each double by repetition; unit preserved.
133
+ ```
134
+
135
+ Use `einshape(x, pattern)` to map named axes to lengths. Use `einreduce()` and `einsum()` through `math-function-library.md` when axes are reduced or contracted.
136
+
137
+ ## Backend conversion
138
+
139
+ All `Quantity` backend methods retain the wrapper and attached unit:
140
+
141
+ | Exact signature | Target mantissa |
142
+ |---|---|
143
+ | `to_jax()` | JAX `Array` |
144
+ | `to_numpy()` | `numpy.ndarray` |
145
+ | `to_cupy(*, device=None)` | `cupy.ndarray` |
146
+ | `to_torch(*, device=None, dtype=None)` | `torch.Tensor` |
147
+ | `to_dask(*, chunks='auto')` | `dask.array.Array` |
148
+ | `to_ndonnx()` | Symbolic `ndonnx.Array` |
149
+
150
+ `u.math.as_numpy(x)` is different: for a `Quantity`, it returns the underlying mantissa in the current unit scale as a NumPy array.
151
+
152
+ ## Source-backed gotchas
153
+
154
+ - `q.at` supports NumPy, JAX, CuPy, Torch, and Dask mantissas. The ndonnx backend raises `BackendError`; the API recommends `.to_numpy()` first.
155
+ - Repeated-index update semantics differ by backend. JAX, NumPy, and CuPy accumulate documented operations; some Torch and Dask operations use last-write-wins behavior.
156
+ - Dask functional updates support slice, scalar integer, 1-D integer, and boolean-mask indices; multidimensional fancy integer indexing raises `NotImplementedError`.
157
+ - `mT` transposes only the last two dimensions and requires at least two dimensions.
158
+ - `u.math.as_numpy(q)` drops the `Quantity` wrapper; `q.to_numpy()` keeps it.
159
+ - In Einstein patterns, axis order inside parentheses changes element order. A literal `1` or `()` creates a length-one axis, and either can be removed in the inverse pattern.
160
+
161
+ ## Sources mirrored
162
+
163
+ - https://brainx.chaobrain.com/brainunit/apis/generated/brainunit.Quantity.html
164
+ - https://brainunit.readthedocs.io/apis/brainunit.math.html
165
+ - https://brainunit.readthedocs.io/unit_operations/einstein_operations.html
@@ -0,0 +1,433 @@
1
+ # Math function library
2
+
3
+ Use this reference after the basic `brainunit.math` workflow is known. Route a function by what it requires from input units and what it does to output units. Array creation and purely structural manipulation are owned by `array-creation.md` and `array-mechanics.md`.
4
+
5
+ ## Contents
6
+
7
+ - [Selection map](#selection-map)
8
+ - [Activation functions](#activation-functions)
9
+ - [Dimensionless evaluation](#dimensionless-evaluation)
10
+ - [Unit-changing operations](#unit-changing-operations)
11
+ - [Unit-preserving operations](#unit-preserving-operations)
12
+ - [Unit-removing operations](#unit-removing-operations)
13
+ - [Reductions and contractions](#reductions-and-contractions)
14
+ - [Einstein operations](#einstein-operations)
15
+ - [Source-backed gotchas](#source-backed-gotchas)
16
+
17
+
18
+
19
+ ## Activation functions
20
+
21
+ Activation functions do not have one shared unit rule. `relu()` and `leaky_relu()` preserve physical units; sigmoid-, exponential-, and gating-style functions evaluate dimensionless magnitudes and return plain arrays.
22
+
23
+ | Exact signature | Use when | One-line description | Code and result |
24
+ |---|---|---|---|
25
+ | `relu(x)` | Need to zero negative physical values without changing their physical kind. | Apply `max(x, 0)` element-wise and preserve the input unit. | `u.math.relu(u.math.array([-1., 2.]) * u.meter)`<br>`# Quantity([0., 2.], "m")` |
26
+ | `sigmoid(x, unit_to_scale=None)` | Need a smooth gate in `(0, 1)` from a dimensionless value or a physical value expressed relative to a chosen scale. | Evaluate the logistic function and return a plain array. | `u.math.sigmoid(u.math.array([-1., 0., 1.]) * u.mV, unit_to_scale=u.mV)`<br>`# Array([0.2689414, 0.5, 0.7310586])` |
27
+ | `softplus(x, unit_to_scale=None)` | Need a smooth approximation to ReLU whose output is dimensionless. | Evaluate `log(1 + exp(x))` after optional unit scaling. | `u.math.softplus(u.math.array([0., 1.]) * u.mV, unit_to_scale=u.mV)`<br>`# Array([0.6931472, 1.3132616])` |
28
+ | `silu(x, unit_to_scale=None)`<br>`swish(x, unit_to_scale=None)` | Need a smooth self-gated activation; `swish` is the same activation family. | Multiply the scaled dimensionless input by its sigmoid and return a plain array. | `u.math.silu(u.math.array([0., 1.]) * u.mV, unit_to_scale=u.mV)`<br>`# Array([0., 0.7310586])` |
29
+ | `glu(x, axis=-1, unit_to_scale=None)` | Need a learned-style gate encoded by splitting one tensor axis in half. | Split an even-length axis into value and sigmoid-gate halves; the output is half as long on that axis. | `x = u.math.array([[1., 2., 3., 4.]]); u.math.glu(x)`<br>`# Array([[0.9525741, 1.9640275]]); shape (1, 2)` |
30
+
31
+ Key rules:
32
+
33
+ - `unit_to_scale` converts a compatible physical input to a dimensionless magnitude before evaluation; it does not attach that unit to the output.
34
+ - `glu()` requires the selected axis length to be divisible by two.
35
+ - `silu()` and `swish()` are aliases at the activation-family level; do not create separate decision paths for them.
36
+
37
+ ### Quick reference
38
+
39
+ | API | Description and result |
40
+ |---|---|
41
+ | `relu6(x, unit_to_scale=None)` | Use when clipping a ReLU response at 6 after optional unit scaling. Returns a plain array. |
42
+ | `sparse_plus(x, unit_to_scale=None)` | Use when applying the sparse-plus activation to a dimensionless or explicitly scaled value. Returns a plain array. |
43
+ | `sparse_sigmoid(x, unit_to_scale=None)` | Use when applying the sparse-sigmoid activation to a dimensionless or explicitly scaled value. Returns a plain array. |
44
+ | `soft_sign(x, unit_to_scale=None)` | Use when smoothly mapping a dimensionless or explicitly scaled value through the soft-sign function. Returns a plain array. |
45
+ | `log_sigmoid(x, unit_to_scale=None)` | Use when computing log-sigmoid values from dimensionless or explicitly scaled input. Returns a plain array. |
46
+ | `leaky_relu(x, negative_slope=0.01)` | Use when retaining a configurable slope for negative physical values. Returns a quantity with the input unit. |
47
+ | `hard_sigmoid(x, unit_to_scale=None)` | Use when a piecewise-linear sigmoid approximation is sufficient. Returns a plain array after optional unit scaling. |
48
+ | `hard_silu(x, unit_to_scale=None)` | Use when a piecewise-linear SiLU approximation is sufficient. Returns a plain array after optional unit scaling. |
49
+ | `hard_swish` | Use when selecting the documented alias of `hard_silu`. Returns the same plain-array result as `hard_silu`. |
50
+ | `hard_tanh(x, unit_to_scale=None)` | Use when clipping a dimensionless or explicitly scaled value to the hard-tanh range. Returns a plain array. |
51
+ | `elu(x, alpha=1.0, unit_to_scale=None)` | Use when applying an exponential linear unit with configurable negative saturation. Returns a plain array. |
52
+ | `celu(x, alpha=1.0, unit_to_scale=None)` | Use when the exponential linear activation must be continuously differentiable. Returns a plain array. |
53
+ | `selu(x, unit_to_scale=None)` | Use when applying the scaled exponential linear unit to dimensionless or explicitly scaled input. Returns a plain array. |
54
+ | `gelu(x, approximate=True, unit_to_scale=None)` | Use when applying a Gaussian error linear unit with exact or approximate evaluation. Returns a plain array. |
55
+ | `squareplus(x, b=4, unit_to_scale=None)` | Use when applying a square-root-based smooth ReLU alternative with configurable `b`. Returns a plain array. |
56
+ | `mish(x, unit_to_scale=None)` | Use when applying the Mish activation to dimensionless or explicitly scaled input. Returns a plain array. |
57
+
58
+ ## Dimensionless evaluation
59
+
60
+ These functions evaluate mathematical operations whose arguments must be dimensionless.
61
+
62
+ | Exact signature | Use when | One-line description | Code and result |
63
+ |---|---|---|---|
64
+ | `exp(x, unit_to_scale=None, **kwargs)` | Need exponential growth from a dimensionless ratio, including a physical value divided by an explicit scale. | Return `e ** x` after optional unit scaling. | `u.math.exp(u.math.array([0., 1.]) * u.mV, unit_to_scale=u.mV)`<br>`# Array([1., 2.7182817])` |
65
+ | `log(x, unit_to_scale=None, **kwargs)` | Need a natural logarithm of a dimensionless ratio. | Return the natural logarithm after optional unit scaling. | `u.math.log(u.math.array([1., 2.7182817]) * u.mV, unit_to_scale=u.mV)`<br>`# Array([0., 1.])` |
66
+ | `hypot(x, y, unit_to_scale=None, **kwargs)` | Need Euclidean magnitude from two compatible components but want a dimensionless result relative to a scale. | Compute `sqrt(x**2 + y**2)` on scaled magnitudes. | `u.math.hypot(3. * u.meter, 4. * u.meter, unit_to_scale=u.meter)`<br>`# Array(5.); plain, not meters` |
67
+ | `arctan2(x, y, unit_to_scale=None, **kwargs)` | Need a quadrant-aware angle from two compatible components. | Compute the signed angle from scaled dimensionless magnitudes. | `u.math.arctan2(1. * u.mV, 1. * u.mV, unit_to_scale=u.mV)`<br>`# Array(0.7853982); radians as a plain value` |
68
+ | `corrcoef(x, y=None, rowvar=True, unit_to_scale=None, **kwargs)` | Need unit-independent linear correlation between variables. | Return Pearson correlation coefficients after optional unit scaling. | `x = u.math.array([[1., 2., 3.], [2., 4., 6.]]) * u.mV; u.math.corrcoef(x, unit_to_scale=u.mV)`<br>`# Array([[1., 1.], [1., 1.]]); shape (2, 2)` |
69
+ | `cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None, unit_to_scale=None, **kwargs)` | Need covariance of values after expressing them relative to a chosen physical scale. | Estimate covariance on dimensionless scaled data. | `x = u.math.array([1., 2., 3.]) * u.mV; u.math.cov(x, unit_to_scale=u.mV)`<br>`# Array(1.); dimensionless sample covariance` |
70
+
71
+ Do not invent arguments for `**kwargs`; forward only backend arguments documented for the active BrainUnit/backend version.
72
+
73
+ For `corrcoef()` and `cov()`, `rowvar=True` treats each row as a variable and columns as observations; use `rowvar=False` when variables are stored in columns. `unit_to_scale` controls the dimensionless magnitudes evaluated, so it also fixes the numerical scale of `cov()`.
74
+
75
+ ### Quick reference
76
+
77
+ | API | Description and result |
78
+ |---|---|
79
+ | `exprel(x, **kwargs)` | Use when evaluating `(exp(x) - 1) / x` accurately near zero. Requires dimensionless input and returns a plain array. |
80
+ | `exp2(x, unit_to_scale=None, **kwargs)` | Use when computing a base-2 exponential of a dimensionless or explicitly scaled value. Returns a plain array. |
81
+ | `expm1(x, unit_to_scale=None, **kwargs)` | Use when computing `exp(x) - 1` accurately near zero from dimensionless or explicitly scaled input. Returns a plain array. |
82
+ | `log2(x, unit_to_scale=None, **kwargs)` | Use when computing a base-2 logarithm of a dimensionless or explicitly scaled value. Returns a plain array. |
83
+ | `log10(x, unit_to_scale=None, **kwargs)` | Use when computing a base-10 logarithm of a dimensionless or explicitly scaled value. Returns a plain array. |
84
+ | `log1p(x, unit_to_scale=None, **kwargs)` | Use when computing `log(1 + x)` accurately near zero from dimensionless or explicitly scaled input. Returns a plain array. |
85
+ | `arccos(x, unit_to_scale=None, **kwargs)` | Use when computing inverse cosine from dimensionless or explicitly scaled input. Returns a plain angle array. |
86
+ | `arccosh(x, unit_to_scale=None, **kwargs)` | Use when computing inverse hyperbolic cosine from dimensionless or explicitly scaled input. Returns a plain array. |
87
+ | `arcsin(x, unit_to_scale=None, **kwargs)` | Use when computing inverse sine from dimensionless or explicitly scaled input. Returns a plain angle array. |
88
+ | `arcsinh(x, unit_to_scale=None, **kwargs)` | Use when computing inverse hyperbolic sine from dimensionless or explicitly scaled input. Returns a plain array. |
89
+ | `arctan(x, unit_to_scale=None, **kwargs)` | Use when computing inverse tangent from dimensionless or explicitly scaled input. Returns a plain angle array. |
90
+ | `arctanh(x, unit_to_scale=None, **kwargs)` | Use when computing inverse hyperbolic tangent from dimensionless or explicitly scaled input. Returns a plain array. |
91
+ | `cos(x, unit_to_scale=None, **kwargs)` | Use when computing cosine of a dimensionless or explicitly scaled value. Returns a plain array. |
92
+ | `cosh(x, unit_to_scale=None, **kwargs)` | Use when computing hyperbolic cosine of a dimensionless or explicitly scaled value. Returns a plain array. |
93
+ | `sin(x, unit_to_scale=None, **kwargs)` | Use when computing sine of a dimensionless or explicitly scaled value. Returns a plain array. |
94
+ | `sinc(x, unit_to_scale=None, **kwargs)` | Use when computing normalized `sin(pi*x) / (pi*x)` from dimensionless or explicitly scaled input. Returns a plain array. |
95
+ | `sinh(x, unit_to_scale=None, **kwargs)` | Use when computing hyperbolic sine of a dimensionless or explicitly scaled value. Returns a plain array. |
96
+ | `tan(x, unit_to_scale=None, **kwargs)` | Use when computing tangent of a dimensionless or explicitly scaled value. Returns a plain array. |
97
+ | `tanh(x, unit_to_scale=None, **kwargs)` | Use when computing hyperbolic tangent of a dimensionless or explicitly scaled value. Returns a plain array. |
98
+ | `deg2rad(x, unit_to_scale=None, **kwargs)` | Use when converting numeric degrees to radians after optional unit scaling. Returns a plain angle array. |
99
+ | `rad2deg(x, unit_to_scale=None, **kwargs)` | Use when converting numeric radians to degrees after optional unit scaling. Returns a plain angle array. |
100
+ | `degrees(x, unit_to_scale=None, **kwargs)` | Use when selecting the documented alias of `rad2deg`. Returns a plain angle array in degrees. |
101
+ | `radians(x, unit_to_scale=None, **kwargs)` | Use when selecting the documented alias of `deg2rad`. Returns a plain angle array in radians. |
102
+ | `angle(x, unit_to_scale=None, **kwargs)` | Use when extracting the phase of a complex argument after optional unit scaling. Returns a plain angle array. |
103
+ | `frexp(x, unit_to_scale=None, **kwargs)` | Use when decomposing dimensionless or explicitly scaled values into base-2 parts. Returns `(mantissa, exponent)` as two plain arrays. |
104
+ | `ldexp(x, y, unit_to_scale=None, **kwargs)` | Use when reconstructing values as `x * 2**y` after optional scaling of `x`. Returns a plain array. |
105
+ | `logaddexp(x, y, unit_to_scale=None, **kwargs)` | Use when stably computing the natural logarithm of summed exponentials. Returns a plain array from dimensionless or explicitly scaled operands. |
106
+ | `logaddexp2(x, y, unit_to_scale=None, **kwargs)` | Use when stably computing the base-2 logarithm of summed base-2 exponentials. Returns a plain array. |
107
+ | `correlate(a, v, mode='valid', *, precision=None, preferred_element_type=None, unit_to_scale=None, **kwargs)` | Use when cross-correlating two one-dimensional sequences. Returns unit `a.unit * v.unit` by default, or a plain array when `unit_to_scale` is supplied. |
108
+ | `set_exprel_order(order)` | Use when trading computation for Taylor-series accuracy in `exprel()` near zero. Accepts orders 2 through 20 and returns `None`. |
109
+ | `bitwise_not(x, **kwargs)` | Use when flipping every bit of dimensionless integer input. Returns a plain integer array. |
110
+ | `invert(x, **kwargs)` | Use when selecting the bitwise-inversion alias of `bitwise_not`. Returns a plain integer array. |
111
+ | `bitwise_and(x, y, **kwargs)` | Use when applying element-wise bitwise AND to dimensionless integer operands. Returns a plain integer array. |
112
+ | `bitwise_or(x, y, **kwargs)` | Use when applying element-wise bitwise OR to dimensionless integer operands. Returns a plain integer array. |
113
+ | `bitwise_xor(x, y, **kwargs)` | Use when applying element-wise bitwise XOR to dimensionless integer operands. Returns a plain integer array. |
114
+ | `left_shift(x, y, **kwargs)` | Use when shifting dimensionless integer bits left by `y`. Returns a plain integer array. |
115
+ | `right_shift(x, y, **kwargs)` | Use when shifting dimensionless integer bits right by `y`. Returns a plain integer array. |
116
+
117
+ ## Unit-changing operations
118
+
119
+ These functions change physical dimensions because they invert, multiply, divide, power, integrate, or contract values.
120
+
121
+ | Exact signature | Use when | One-line description | Code and result |
122
+ |---|---|---|---|
123
+ | `reciprocal(x, **kwargs)` | Need the multiplicative inverse of a physical value. | Invert the value and its unit. | `u.math.reciprocal(2. * u.second)`<br>`# Quantity(0.5, "s^-1")` |
124
+ | `multiply(x, y, **kwargs)` | Need element-wise products with broadcasted operands. | Multiply values and input units element-wise. | `u.math.multiply(2. * u.meter, 3. * u.second)`<br>`# Quantity(6., "m s")` |
125
+ | `divide(x, y, **kwargs)` | Need an element-wise physical ratio. | Divide values and input units element-wise. | `u.math.divide(6. * u.meter, 2. * u.second)`<br>`# Quantity(3., "m / s")` |
126
+ | `power(x, y, **kwargs)` | Need element-wise exponentiation with a dimensionless exponent. | Raise each value and its unit to `y`. | `u.math.power(2. * u.meter, 3)`<br>`# Quantity(8., "m^3")` |
127
+ | `square(x, **kwargs)` | Need the element-wise square of a physical value. | Square the value and input unit. | `u.math.square(3. * u.meter)`<br>`# Quantity(9., "m^2")` |
128
+ | `sqrt(x, **kwargs)` | Need a principal square root with the corresponding root unit. | Take the square root of the value and unit. | `u.math.sqrt(9. * (u.meter ** 2))`<br>`# Quantity(3., "m")` |
129
+ | `prod(x, axis=None, dtype=None, keepdims=False, initial=None, where=None)` | Need to multiply all elements along an axis rather than add them. | Multiply selected elements and raise the unit to the number reduced. | `x = u.math.array([2., 3.]) * u.meter; u.math.prod(x)`<br>`# Quantity(6., "m^2")` |
130
+ | `var(a, axis=None, dtype=None, ddof=0, keepdims=False, *, where=None, **kwargs)` | Need spread expressed in squared physical units. | Compute variance; the output unit is the square of the input unit. | `x = u.math.array([1., 2., 3.]) * u.meter; u.math.var(x)`<br>`# Quantity(0.6666667, "m^2")` |
131
+ | `dot(a, b, *, precision=None, preferred_element_type=None, **kwargs)` | Need a vector dot product or general backend dot semantics. | Contract the dot axes and multiply operand units. | `a = u.math.array([1., 2.]) * u.meter; b = u.math.array([3., 4.]) * u.second; u.math.dot(a, b)`<br>`# Quantity(11., "m s"); scalar` |
132
+ | `matmul(a, b, *, precision=None, preferred_element_type=None, **kwargs)` | Need conventional matrix or batched matrix multiplication. | Contract matrix axes, broadcast batch axes, and multiply units. | `a = u.math.array([[1., 2.]]) * u.meter; b = u.math.array([[3.], [4.]]) * u.second; u.math.matmul(a, b)`<br>`# Quantity([[11.]], "m s"); shape (1, 1)` |
133
+ | `tensordot(a, b, axes=2, precision=None, preferred_element_type=None, **kwargs)` | Need to choose exactly which tensor axes are contracted. | Sum products over `axes` and multiply operand units. | `a = u.math.array([1., 2.]) * u.meter; b = u.math.array([3., 4.]) * u.second; u.math.tensordot(a, b, axes=1)`<br>`# Quantity(11., "m s"); scalar` |
134
+ | `matrix_power(a, n, **kwargs)` | Need an integer power of a square matrix. | Repeatedly multiply the matrix; the output unit is `a.unit ** n`. | `a = u.math.array([[2., 0.], [0., 3.]]) * u.meter; u.math.matrix_power(a, 2)`<br>`# Quantity([[4., 0.], [0., 9.]], "m^2")` |
135
+
136
+ Key rules:
137
+
138
+ - `power()` requires a dimensionless exponent.
139
+ - `prod()` uses `x.unit ** n`, where `n` is the number of elements reduced. A unitful `initial` raises `TypeError`.
140
+ - `dot()`, `matmul()`, and `tensordot()` all multiply operand units; choose among them by contraction semantics, not unit behavior.
141
+
142
+ | API | Description and result |
143
+ |---|---|
144
+ | `cbrt(x, **kwargs)` | Use when taking element-wise cube roots of physical values. Returns a quantity with unit `x.unit ** (1/3)`. |
145
+ | `float_power(x, y, **kwargs)` | Use when power results must be inexact with at least float64 precision. Returns a quantity with unit `x.unit ** y`, and `y` must be dimensionless. |
146
+ | `cumprod(x, axis=None, dtype=None, **kwargs)` | Use when accumulating products along an axis. Returns cumulative values whose unit power grows with the number of factors. |
147
+ | `cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None, **kwargs)` | Use when computing vector cross products with configurable vector axes. Returns a quantity with unit `a.unit * b.unit`. |
148
+ | `floor_divide(x, y, **kwargs)` | Use when element-wise quotient values must be floored. Same-dimension inputs return plain integers; mixed dimensions return the base quotient unit. |
149
+ | `divmod(x, y, **kwargs)` | Use when both floored quotient and remainder are needed. Returns a tuple whose quotient follows `floor_divide` and whose remainder carries the dividend's physical kind. |
150
+ | `convolve(a, v, mode='full', *, precision=None, preferred_element_type=None, **kwargs)` | Use when computing discrete linear convolution of one-dimensional sequences. Returns a quantity with unit `a.unit * v.unit`. |
151
+ | `trapezoid(y, x=None, dx=1.0, axis=-1)` | Use when integrating sampled values with the composite trapezoidal rule. Returns unit `y.unit * x.unit`, or `y.unit * dx.unit` when `x` is omitted. |
152
+ | `multi_dot(arrays, *, precision=None, **kwargs)` | Use when multiplying a chain of matrices with an efficient contraction order. Returns a quantity whose unit is the product of all operand units. |
153
+ | `vdot(a, b, *, precision=None, preferred_element_type=None, **kwargs)` | Use when flattening two inputs and conjugating the first before their dot product. Returns unit `a.unit * b.unit`. |
154
+ | `vecdot(a, b, /, *, axis=-1, precision=None, preferred_element_type=None, **kwargs)` | Use when computing conjugate batched vector products along a chosen axis. Returns unit `a.unit * b.unit` with that axis removed. |
155
+ | `inner(a, b, *, precision=None, preferred_element_type=None, **kwargs)` | Use when contracting the last axes of two inputs. Returns a quantity with unit `a.unit * b.unit`. |
156
+ | `outer(a, b, out=None, **kwargs)` | Use when forming every pairwise product of flattened inputs. Returns an `(a.size, b.size)` quantity with unit `a.unit * b.unit`. |
157
+ | `kron(a, b, **kwargs)` | Use when forming a Kronecker product. Returns a quantity with combined shape and unit `a.unit * b.unit`. |
158
+ | `true_divide(x, y, **kwargs)` | Use when selecting the true-division alias of `divide`. Returns a quantity with unit `x.unit / y.unit`. |
159
+ | `product` | Use when selecting the documented alias of `prod`. Returns the same product and unit-exponent behavior as `prod`. |
160
+ | `cumproduct` | Use when selecting the documented alias of `cumprod`. Returns the same cumulative values and unit powers as `cumprod`. |
161
+ | `nanprod(x, axis=None, dtype=None, keepdims=False, initial=None, where=None, **kwargs)` | Use when multiplying along an axis while treating NaNs as one. Returns a quantity whose unit is raised to the number of reduced elements. |
162
+ | `nancumprod(x, axis=None, dtype=None, **kwargs)` | Use when accumulating products while treating NaNs as one. Returns cumulative values with corresponding cumulative unit powers. |
163
+ | `nanvar(x, axis=None, dtype=None, ddof=0, keepdims=False, where=None, **kwargs)` | Use when computing variance while ignoring NaNs. Returns a quantity whose unit is the square of the input unit. |
164
+
165
+ ## Unit-preserving operations
166
+
167
+ These functions return values of the same physical kind as their primary input. Bounds, branches, interpolation coordinates, and replacement values must still be compatible with the quantities they constrain.
168
+
169
+ | Exact signature | Use when | One-line description | Code and result |
170
+ |---|---|---|---|
171
+ | `where(condition, x=None, y=None, /, *, size=None, fill_value=None, **kwargs)` | Need element-wise selection between two unit-compatible branches. | Choose from `x` where true and `y` otherwise, preserving the branch unit. | `a = u.math.array([1., 2.]) * u.meter; u.math.where(u.math.array([True, False]), a, 0. * u.meter)`<br>`# Quantity([1., 0.], "m")` |
172
+ | `clip(a, a_min, a_max, **kwargs)` | Need to enforce lower and upper physical bounds. | Clamp values to compatible bounds and preserve `a`'s unit. | `a = u.math.array([0., 2., 4.]) * u.meter; u.math.clip(a, 1. * u.meter, 3. * u.meter)`<br>`# Quantity([1., 2., 3.], "m")` |
173
+ | `interp(x, xp, fp, left=None, right=None, period=None, **kwargs)` | Need one-dimensional interpolation with physical coordinates and physical results. | Interpolate along coordinates compatible with `xp`; `fp` determines the output unit. | `xp = u.math.array([0., 1.]) * u.second; fp = u.math.array([0., 10.]) * u.meter; u.math.interp(0.5 * u.second, xp, fp)`<br>`# Quantity(5., "m")` |
174
+ | `histogram(x, bins=10, range=None, weights=None, density=None, **kwargs)` | Need counts over physical bins while retaining physical bin edges. | Return histogram values plus bin edges compatible with `x`. | `x = u.math.array([1., 2., 3.]) * u.second; bins = u.math.array([0., 2., 4.]) * u.second; u.math.histogram(x, bins=bins)`<br>`# (Array([1, 2]), Quantity([0., 2., 4.], "s"))` |
175
+ | `nan_to_num(x, nan=None, posinf=None, neginf=None, **kwargs)` | Need to replace non-finite physical values without dropping units. | Replace NaN/infinities with compatible values and preserve `x`'s unit. | `x = u.math.array([float('nan'), 1.]) * u.meter; u.math.nan_to_num(x, nan=0. * u.meter)`<br>`# Quantity([0., 1.], "m")` |
176
+ | `percentile(a, q, axis=None, method='linear', keepdims=False, **kwargs)`<br>`quantile(a, q, axis=None, method='linear', keepdims=False, **kwargs)` | Need percentile or quantile summaries while preserving physical kind. | Use percentile scale `0..100` or quantile scale `0..1`; both preserve the input unit. | `x = u.math.array([0., 10.]) * u.meter; (u.math.percentile(x, 50), u.math.quantile(x, 0.5))`<br>`# (Quantity(5., "m"), Quantity(5., "m"))` |
177
+ | `promote_dtypes(*args, **kwargs)` | Need several inputs to share a numeric dtype without changing their units. | Promote mantissa dtypes to the most precise input type while retaining each input shape and unit. | `a = u.math.array([1]) * u.second; b = u.math.array([2.5]) * u.second; pa, pb = u.math.promote_dtypes(a, b); (pa.unit, pb.unit, pa.dtype == pb.dtype)`<br>`# (u.second, u.second, True)` |
178
+
179
+ Key rules:
180
+
181
+ - With three arguments, `where()` requires `condition`, `x`, and `y` to broadcast together and requires compatible branch values. With only `condition`, prefer `nonzero()`.
182
+ - `interp()` requires increasing `xp`; `x`, `xp`, and any `period` must be coordinate-compatible, while `left` and `right` must match `fp`.
183
+ - `histogram()` returns plain counts when unweighted; quantity weights or `density=True` change histogram-value semantics, while physical bin edges remain compatible with `x`.
184
+
185
+ ### Quick reference
186
+
187
+ | API | Description and result |
188
+ |---|---|
189
+ | `sort(a, axis=-1, *, kind=None, order=None, stable=True, descending=False, **kwargs)` | Use when ordering physical values along an axis. Returns a same-shape quantity with the input unit. |
190
+ | `max(a, axis=None, keepdims=False, initial=None, where=None, **kwargs)` | Use when selecting maximum physical values over chosen axes. Returns a quantity with the input unit. |
191
+ | `min(a, axis=None, keepdims=False, initial=None, where=None, **kwargs)` | Use when selecting minimum physical values over chosen axes. Returns a quantity with the input unit. |
192
+ | `amax` | Use when selecting the documented alias of `max`. Returns the same maximum values with the input unit. |
193
+ | `amin` | Use when selecting the documented alias of `min`. Returns the same minimum values with the input unit. |
194
+ | `ptp(x, axis=None, keepdims=False, **kwargs)` | Use when measuring peak-to-peak range as maximum minus minimum. Returns a quantity with the input unit. |
195
+ | `sum(x, axis=None, dtype=None, keepdims=False, initial=None, where=None)` | Use when computing additive totals over chosen axes. Returns a quantity with the input unit. |
196
+ | `cumsum(x, axis=None, dtype=None, **kwargs)` | Use when computing cumulative additive totals along an axis. Returns a same-shape quantity with the input unit. |
197
+ | `median(x, axis=None, overwrite_input=False, keepdims=False, **kwargs)` | Use when computing median physical values over chosen axes. Returns a quantity with the input unit. |
198
+ | `average(x, axis=None, weights=None, returned=False, keepdims=False, **kwargs)` | Use when computing a weighted physical mean. Returns the average with the input unit and, with `returned=True`, also the plain sum of weights. |
199
+ | `mean(x, axis=None, dtype=None, keepdims=False, *, where=None, **kwargs)` | Use when computing arithmetic means over chosen axes. Returns a quantity with the input unit. |
200
+ | `std(x, axis=None, dtype=None, ddof=0, keepdims=False, *, where=None, **kwargs)` | Use when measuring spread in the original physical kind. Returns a quantity with the input unit. |
201
+ | `real(x, **kwargs)` | Use when extracting real components of complex physical values. Returns a quantity with the input unit. |
202
+ | `imag(x, **kwargs)` | Use when extracting imaginary components of complex physical values. Returns a quantity with the input unit. |
203
+ | `conj(x, **kwargs)` | Use when conjugating complex physical values. Returns a quantity with the input unit. |
204
+ | `negative(x, **kwargs)` | Use when negating physical values element-wise. Returns a quantity with the input unit. |
205
+ | `positive(x, **kwargs)` | Use when applying unary plus to physical values. Returns a quantity with the input unit. |
206
+ | `abs(x, **kwargs)` | Use when taking element-wise magnitudes of physical values. Returns a quantity with the input unit. |
207
+ | `fabs(x, **kwargs)` | Use when taking floating-point absolute values. Returns a quantity with the input unit. |
208
+ | `round(x, decimals=0, **kwargs)` | Use when rounding physical mantissas to a chosen number of decimals. Returns a quantity with the input unit. |
209
+ | `rint(x, **kwargs)` | Use when rounding physical mantissas to nearest integers. Returns a quantity with the input unit. |
210
+ | `floor(x, **kwargs)` | Use when rounding physical mantissas down. Returns a quantity with the input unit. |
211
+ | `ceil(x, **kwargs)` | Use when rounding physical mantissas up. Returns a quantity with the input unit. |
212
+ | `trunc(x, **kwargs)` | Use when discarding fractional mantissa parts. Returns a quantity with the input unit. |
213
+ | `fix(x, **kwargs)` | Use when rounding physical mantissas toward zero. Returns a quantity with the input unit. |
214
+ | `add(x, y, **kwargs)` | Use when adding broadcast-compatible physical values. Returns a quantity in the operands' common physical kind. |
215
+ | `subtract(x, y, **kwargs)` | Use when subtracting broadcast-compatible physical values. Returns a quantity in the operands' common physical kind. |
216
+ | `maximum(x1, x2, **kwargs)` | Use when selecting element-wise maxima from compatible physical values. Returns a quantity with the shared physical unit. |
217
+ | `minimum(x1, x2, **kwargs)` | Use when selecting element-wise minima from compatible physical values. Returns a quantity with the shared physical unit. |
218
+ | `fmax(x1, x2, **kwargs)` | Use when selecting element-wise maxima while ignoring NaNs. Returns a quantity with the shared physical unit. |
219
+ | `fmin(x1, x2, **kwargs)` | Use when selecting element-wise minima while ignoring NaNs. Returns a quantity with the shared physical unit. |
220
+ | `ediff1d(x, to_end=None, to_begin=None, **kwargs)` | Use when computing consecutive differences on flattened physical data. Returns a one-dimensional quantity with the input unit. |
221
+ | `diff(x, n=1, axis=-1, prepend=None, append=None, **kwargs)` | Use when computing repeated consecutive differences along an axis. Returns a quantity with the input unit and a shortened selected axis. |
222
+ | `modf(x, **kwargs)` | Use when splitting physical mantissas into fractional and integral parts. Returns two quantities with the input unit. |
223
+ | `fmod(x1, x2, **kwargs)` | Use when computing truncation-based remainders of compatible physical values. Returns a quantity with the shared physical unit. |
224
+ | `mod(x1, x2, **kwargs)` | Use when computing element-wise modulus of compatible physical values. Returns a quantity with the shared physical unit. |
225
+ | `remainder(x, y, **kwargs)` | Use when computing floor-division remainders of compatible physical values. Returns a quantity in the dividend's physical kind. |
226
+ | `copysign(x1, x2, **kwargs)` | Use when copying signs between compatible physical values. Returns a quantity with the shared unit. |
227
+ | `nextafter(x, y, **kwargs)` | Use when finding the next representable physical value from `x` toward compatible `y`. Returns a quantity with `x`'s unit. |
228
+ | `lcm(x1, x2, **kwargs)` | Use when computing element-wise least common multiples of compatible integer quantities. Returns a quantity with the shared unit. |
229
+ | `gcd(x1, x2, **kwargs)` | Use when computing element-wise greatest common divisors of compatible integer quantities. Returns a quantity with the shared unit. |
230
+ | `trace(a, offset=0, axis1=0, axis2=1, dtype=None, **kwargs)` | Use when summing a selected matrix diagonal. Returns a quantity with the input unit and removes the two traced axes. |
231
+ | `select(condlist, choicelist, default=0, **kwargs)` | Use when choosing among ordered condition branches. Returns a quantity when the choices resolve to a compatible physical kind. |
232
+ | `conjugate(x, **kwargs)` | Use when selecting the documented alias of `conj`. Returns a quantity with the input unit. |
233
+ | `absolute(x, **kwargs)` | Use when selecting the documented alias of `abs`. Returns a quantity with the input unit. |
234
+ | `around(x, decimals=0, **kwargs)` | Use when selecting the documented alias of `round`. Returns a quantity with the input unit. |
235
+ | `nancumsum(x, axis=None, dtype=None, **kwargs)` | Use when accumulating sums while treating NaNs as zero. Returns a same-shape quantity with the input unit. |
236
+ | `nansum(x, axis=None, dtype=None, keepdims=False, initial=None, where=None, **kwargs)` | Use when summing physical values while ignoring NaNs. Returns a quantity with the input unit. |
237
+ | `nanmin(x, axis=None, keepdims=False, initial=None, where=None, **kwargs)` | Use when selecting minimum physical values while ignoring NaNs. Returns a quantity with the input unit. |
238
+ | `nanmax(x, axis=None, keepdims=False, initial=None, where=None, **kwargs)` | Use when selecting maximum physical values while ignoring NaNs. Returns a quantity with the input unit. |
239
+ | `nanmedian(x, axis=None, overwrite_input=False, keepdims=False, **kwargs)` | Use when computing median physical values while ignoring NaNs. Returns a quantity with the input unit. |
240
+ | `nanmean(x, axis=None, dtype=None, keepdims=False, *, where=None, **kwargs)` | Use when computing arithmetic means while ignoring NaNs. Returns a quantity with the input unit. |
241
+ | `nanstd(x, axis=None, dtype=None, ddof=0, keepdims=False, *, where=None, **kwargs)` | Use when computing standard deviation while ignoring NaNs. Returns a quantity with the input unit. |
242
+ | `nanpercentile(a, q, axis=None, method='linear', keepdims=False, **kwargs)` | Use when computing percentiles while ignoring NaNs. Returns a quantity with the input unit. |
243
+ | `nanquantile(a, q, axis=None, method='linear', keepdims=False, **kwargs)` | Use when computing quantiles while ignoring NaNs. Returns a quantity with the input unit. |
244
+ | `rot90(m, k=1, axes=(0, 1), **kwargs)` | Use when rotating physical array data by quarter turns in an axis plane. Returns a quantity with the input unit and rotated shape. |
245
+ | `intersect1d(ar1, ar2, assume_unique=False, return_indices=False, **kwargs)` | Use when finding sorted unique values common to compatible inputs. Returns a quantity with the common unit and optional plain index arrays. |
246
+ | `compress(condition, a, axis=None, *, size=None, fill_value=None, **kwargs)` | Use when selecting slices with a boolean condition. Returns a quantity with `a`'s unit and a selection-dependent axis length. |
247
+ | `extract(condition, arr, *, size=None, fill_value=None, **kwargs)` | Use when extracting elements that satisfy a boolean condition. Returns a quantity with `arr`'s unit and optional fixed output size. |
248
+ | `take(a, indices, axis=None, mode=None, unique_indices=False, indices_are_sorted=False, fill_value=None, **kwargs)` | Use when gathering indexed values along an axis. Returns the same array type and unit as `a`. |
249
+ | `choose(a, choices, mode='raise', **kwargs)` | Use when an integer index array selects among broadcast-compatible choices. Returns a quantity when the choices carry a common unit. |
250
+ | `unique(a, return_index=False, return_inverse=False, return_counts=False, axis=None, *, equal_nan=False, size=None, fill_value=None, **kwargs)` | Use when deduplicating physical values. Returns sorted unique values with the input unit plus requested plain index/count arrays. |
251
+ | `gather(input, dim, index, **kwargs)` | Use when gathering values along `dim` with an index array. Returns a quantity with the input unit and the index shape. |
252
+
253
+ ## Unit-removing operations
254
+
255
+ These functions return booleans, indices, counts, signs, or inspection metadata. Some accept physical input and remove its unit because the result is not a physical magnitude. Logical reductions such as `all()` and `any()` are different: their inputs must already be dimensionless.
256
+
257
+
258
+ | Exact signature | Use when | One-line description | Code and result |
259
+ |---|---|---|---|
260
+ | `equal(x, y, *args, **kwargs)` | Need exact element-wise equality between compatible physical values. | Convert two quantities to compatible units and return booleans. | `u.math.equal(1. * u.meter, 100. * u.cm)`<br>`# Array(True); boolean, therefore unitless` |
261
+ | `isclose(x, y, rtol=None, atol=None, equal_nan=False, **kwargs)` | Need element-wise tolerance comparison of physical values. | Compare compatible values and return one boolean per element. | `u.math.isclose(1. * u.meter, 100.1 * u.cm, atol=2. * u.mm)`<br>`# Array(True)` |
262
+ | `allclose(x, y, rtol=None, atol=None, equal_nan=False, **kwargs)` | Need one boolean stating whether all physical values are close. | Reduce element-wise tolerance comparisons to one boolean. | `a = u.math.array([1., 2.]) * u.meter; b = u.math.array([100., 200.1]) * u.cm; u.math.allclose(a, b, atol=2. * u.mm)`<br>`# Array(True)` |
263
+ | `searchsorted(a, v, side='left', sorter=None, *, method='scan', **kwargs)` | Need insertion positions for compatible physical values in sorted data. | Convert `v` to `a`'s unit and return integer insertion indices. | `a = u.math.array([1., 2., 3.]) * u.second; u.math.searchsorted(a, 2500. * u.ms)`<br>`# Array(2); index, therefore unitless` |
264
+ | `argmax(a, axis=None, **kwargs)` | Need the position of the largest physical value. | Strip units for ordering and return an index. | `x = u.math.array([1., 3., 2.]) * u.meter; u.math.argmax(x)`<br>`# Array(1); index` |
265
+ | `nonzero(a, *, size=None, fill_value=None, **kwargs)` | Need coordinates of nonzero physical values. | Strip units and return one index array per dimension. | `x = u.math.array([0., 2., 0.]) * u.meter; u.math.nonzero(x)`<br>`# (Array([1]),); tuple of index arrays` |
266
+ | `count_nonzero(a, axis=None, keepdims=None, **kwargs)` | Need the number of nonzero physical values. | Strip units and return an integer count. | `x = u.math.array([0., 2., 3.]) * u.meter; u.math.count_nonzero(x)`<br>`# Array(2); count` |
267
+ | `all(x, axis=None, keepdims=False, where=None, **kwargs)` | Need to know whether every dimensionless element is truthy. | Perform logical AND reduction on dimensionless input. | `u.math.all(u.math.array([True, True, False]))`<br>`# Array(False)` |
268
+ | `any(x, axis=None, keepdims=False, where=None, **kwargs)` | Need to know whether any dimensionless element is truthy. | Perform logical OR reduction on dimensionless input. | `u.math.any(u.math.array([False, False, True]))`<br>`# Array(True)` |
269
+
270
+ Key rules:
271
+
272
+ - `equal()` converts `y` to `x`'s unit when both are quantities; it raises `TypeError` when only one operand has units.
273
+ - `isclose()` and `allclose()` return booleans. Match `atol` to the compared physical dimension.
274
+ - `all()` and `any()` reject physical input with `TypeError`; they do not interpret nonzero physical magnitudes as truth values.
275
+ - `size` on `nonzero()` fixes result length for compiled code; `fill_value` supplies padding indices, not physical values.
276
+
277
+ ### Quick reference
278
+
279
+ | API | Description and result |
280
+ |---|---|
281
+ | `not_equal(x, y, *args, **kwargs)` | Use when testing element-wise inequality of compatible physical values. Returns a plain boolean array. |
282
+ | `greater(x, y, *args, **kwargs)` | Use when testing whether compatible physical values in `x` exceed `y`. Returns a plain boolean array. |
283
+ | `greater_equal(x, y, *args, **kwargs)` | Use when testing whether compatible physical values in `x` meet or exceed `y`. Returns a plain boolean array. |
284
+ | `less(x, y, *args, **kwargs)` | Use when testing whether compatible physical values in `x` are below `y`. Returns a plain boolean array. |
285
+ | `less_equal(x, y, *args, **kwargs)` | Use when testing whether compatible physical values in `x` are at most `y`. Returns a plain boolean array. |
286
+ | `array_equal(x, y, *args, **kwargs)` | Use when requiring two compatible arrays to have identical shapes and values. Returns one plain boolean. |
287
+ | `logical_not(x, **kwargs)` | Use when negating dimensionless truth values element-wise. Returns a plain boolean array. |
288
+ | `logical_and(x, y, *args, **kwargs)` | Use when combining dimensionless truth values with element-wise AND. Returns a plain boolean array. |
289
+ | `logical_or(x, y, *args, **kwargs)` | Use when combining dimensionless truth values with element-wise OR. Returns a plain boolean array. |
290
+ | `logical_xor(x, y, *args, **kwargs)` | Use when combining dimensionless truth values with element-wise XOR. Returns a plain boolean array. |
291
+ | `argsort(a, axis=-1, *, kind=None, order=None, stable=True, descending=False, **kwargs)` | Use when finding the permutation that orders physical values along an axis. Returns a plain integer index array with `a`'s shape. |
292
+ | `argmin(a, axis=None, keepdims=None, **kwargs)` | Use when locating minimum physical values over an axis. Returns plain integer indices, optionally retaining the reduced axis. |
293
+ | `argwhere(a, *, size=None, fill_value=None, **kwargs)` | Use when finding coordinates of nonzero physical values. Returns a plain integer array with one coordinate row per match. |
294
+ | `flatnonzero(a, *, size=None, fill_value=None, **kwargs)` | Use when finding nonzero positions in flattened physical data. Returns a one-dimensional plain index array. |
295
+ | `digitize(x, bins, right=False, **kwargs)` | Use when assigning compatible physical values to monotonic bins. Returns a plain integer array with the same shape as `x`. |
296
+ | `heaviside(x1, x2, **kwargs)` | Use when mapping physical values to a Heaviside step with dimensionless zero value `x2`. Returns a dimensionless array. |
297
+ | `signbit(x, **kwargs)` | Use when testing whether physical values have their sign bit set. Returns a plain boolean array. |
298
+ | `sign(x, **kwargs)` | Use when extracting only the sign of physical values. Returns a plain dimensionless array. |
299
+ | `nanargmax(a, axis=None, keepdims=False, **kwargs)` | Use when locating maximum physical values while ignoring NaNs. Returns plain integer indices. |
300
+ | `nanargmin(a, axis=None, keepdims=False, **kwargs)` | Use when locating minimum physical values while ignoring NaNs. Returns plain integer indices. |
301
+ | `alltrue` | Use when selecting the documented alias of `all`. Requires dimensionless input and returns a plain boolean result. |
302
+ | `sometrue` | Use when selecting the documented alias of `any`. Requires dimensionless input and returns a plain boolean result. |
303
+ | `iscomplexobj(x, **kwargs)` | Use when inspecting whether a value or array has a complex type. Returns one plain Python boolean. |
304
+ | `get_promote_dtypes(*args, **kwargs)` | Use when determining the common promoted dtype for several inputs. Returns dtype metadata rather than a quantity. |
305
+ | `diag_indices_from(arr, **kwargs)` | Use when obtaining indices for the main diagonal of an array. Returns a tuple of plain integer index arrays. |
306
+ | `bincount(x, weights=None, minlength=0, *, length=None, **kwargs)` | Use when counting occurrences of dimensionless non-negative integers. Returns a plain count or weighted-sum array indexed by input value. |
307
+
308
+ ## Reductions and contractions
309
+
310
+ Choose a reduction by the physical question, then choose axes and shape retention.
311
+
312
+ | Physical question | Exact signature | Unit behavior | Axis and shape rule |
313
+ |---|---|---|---|
314
+ | What is the additive total? | `sum(x, axis=None, dtype=None, keepdims=False, initial=None, where=None)` | Preserves the input unit. | `axis=None` reduces all axes; an integer or tuple selects axes. `keepdims=True` leaves reduced axes at size one. |
315
+ | What is the arithmetic center? | `mean(x, axis=None, dtype=None, keepdims=False, *, where=None, **kwargs)` | Preserves the input unit. | Same reduction-axis and `keepdims` behavior as `sum()`. |
316
+ | What is the spread in the original physical kind? | `std(x, axis=None, dtype=None, ddof=0, keepdims=False, *, where=None, **kwargs)` | Preserves the input unit. | `axis` selects populations; `keepdims=True` supports broadcasting back to `x`. |
317
+ | What is the squared spread? | `var(a, axis=None, dtype=None, ddof=0, keepdims=False, *, where=None, **kwargs)` | Squares the input unit. | Axis and `keepdims` follow `std()`; `ddof` changes the divisor `N - ddof`. |
318
+ | What is the multiplicative accumulation? | `prod(x, axis=None, dtype=None, keepdims=False, initial=None, where=None)` | Raises the input unit to the number of reduced factors. | `axis` determines both output shape and unit exponent; `keepdims` retains reduced axes at size one. |
319
+ | What is the dot product under backend dot rules? | `dot(a, b, *, precision=None, preferred_element_type=None, **kwargs)` | Multiplies operand units. | Contraction axes follow `dot()` rank rules; there is no `axis` or `keepdims` argument. |
320
+ | What is the matrix or batched matrix product? | `matmul(a, b, *, precision=None, preferred_element_type=None, **kwargs)` | Multiplies operand units. | Contracts matrix inner dimensions and broadcasts batch dimensions. |
321
+ | What tensor axes should be contracted explicitly? | `tensordot(a, b, axes=2, precision=None, preferred_element_type=None, **kwargs)` | Multiplies operand units. | Integer `N` contracts the last `N` axes of `a` with the first `N` of `b`; axis sequences choose explicit pairs. |
322
+
323
+ Choice rules:
324
+
325
+ - Use `sum()`, not `prod()`, for additive totals. `prod()` changes the physical dimension as the factor count changes.
326
+ - Use `std()` when the result must remain directly comparable with the input; use `var()` when squared spread is the intended quantity.
327
+ - Use `dot()` for vector dot/general rank-dependent dot semantics, `matmul()` for matrix and batched matrix multiplication, and `tensordot()` for explicit contraction axes.
328
+ - For reducers, `axis=None` flattens conceptually, an integer removes one axis, a tuple reduces several axes, and `keepdims=True` retains each reduced axis with length one.
329
+
330
+ The original worked example, extended to cover all eight choices:
331
+
332
+ ```python
333
+ import brainunit as u
334
+
335
+ x = u.math.asarray([1.0, 2.0, 3.0], unit=u.meter)
336
+
337
+ total = u.math.sum(x)
338
+ # Expected: 6 m.
339
+ center = u.math.mean(x)
340
+ # Expected: 2 m.
341
+ spread = u.math.std(x)
342
+ # Expected: sqrt(2/3) m, approximately 0.8165 m.
343
+ spread2 = u.math.var(x)
344
+ # Expected: 2/3 m^2, approximately 0.6667 m^2.
345
+ product = u.math.prod(x)
346
+ # Expected: 6 m^3.
347
+ area_terms = u.math.square(x)
348
+ # Expected: [1, 4, 9] m^2.
349
+
350
+ a = u.math.array([1.0, 2.0]) * u.meter
351
+ b = u.math.array([3.0, 4.0]) * u.second
352
+ inner = u.math.dot(a, b)
353
+ # Expected: scalar 11 m s.
354
+ explicit_inner = u.math.tensordot(a, b, axes=1)
355
+ # Expected: scalar 11 m s.
356
+
357
+ matrix = u.math.array([[1.0, 2.0]]) * u.meter
358
+ column = u.math.array([[3.0], [4.0]]) * u.second
359
+ matrix_product = u.math.matmul(matrix, column)
360
+ # Expected: shape (1, 1), value [[11]] m s.
361
+ ```
362
+
363
+ ## Einstein operations
364
+
365
+ ### `einreduce`
366
+
367
+ | Exact signature | Use when | Pattern, reduction, shape, and unit |
368
+ |---|---|---|
369
+ | `einreduce(x, pattern, reduction, **axes_lengths)` | Need a readable named-axis reduction combined with splitting, merging, or reordering axes. | Read `pattern` as `input axes -> output axes`. An input axis absent from the output is reduced. Parentheses compose or decompose axes; `axes_lengths` resolves named factors. The output shape follows the right side. `mean`, `min`, `max`, and `sum` preserve the input unit; `prod` raises it according to the number of reduced factors. |
370
+
371
+ ```python
372
+ import brainunit as u
373
+
374
+ x = u.math.ones((1, 4, 4, 1)) * u.mV
375
+ pooled = u.math.einreduce(
376
+ x,
377
+ 'b (h h2) (w w2) c -> b h w c',
378
+ 'mean',
379
+ h2=2,
380
+ w2=2,
381
+ )
382
+ # Expected: shape (1, 2, 2, 1), every value 1 mV.
383
+ ```
384
+
385
+ Here `h2` and `w2` are absent from the output, so each `2 x 2` block is reduced. Changing `mean` to `sum` keeps millivolts but changes values; changing it to `prod` makes each block's result carry `mV ** 4`.
386
+
387
+ ### `einsum`
388
+
389
+ | Exact signature | Use when | Subscripts, reduction, shape, and unit |
390
+ |---|---|---|
391
+ | `einsum(subscripts, /, *operands, optimize='optimal', precision=None, preferred_element_type=None)` | Need a general inner product, matrix multiplication, outer product, reduction, or axis reordering expressed in Einstein notation. | Each operand maps to the labels before `->`; labels on the right determine output-axis order. Repeated labels across operands are multiplied element-wise, and labels omitted from the output are summed. Output shape is formed from retained labels. Contractions multiply operand units; additive reduction alone preserves the operand unit. |
392
+
393
+ Vector inner product: `i` is repeated and omitted from the output, so it is contracted to a scalar.
394
+
395
+ ```python
396
+ import brainunit as u
397
+
398
+ x = u.math.array([1.0, 2.0]) * u.meter
399
+ y = u.math.array([3.0, 4.0]) * u.second
400
+ inner = u.math.einsum('i,i->', x, y)
401
+ # Expected: scalar 11 m s.
402
+ ```
403
+
404
+ Matrix multiplication: `j` is repeated and omitted, while `i` and `k` remain in output order.
405
+
406
+ ```python
407
+ import brainunit as u
408
+
409
+ a = u.math.array([[1.0, 2.0], [3.0, 4.0]]) * u.meter
410
+ b = u.math.array([[3.0], [4.0]]) * u.second
411
+ product = u.math.einsum('ij,jk->ik', a, b)
412
+ # Expected: shape (2, 1), values [[11], [25]] m s.
413
+ ```
414
+
415
+ Use `einrearrange()` and `einrepeat()` through `array-mechanics.md` when element count is preserved or increased rather than reduced.
416
+
417
+ ## Source-backed gotchas
418
+
419
+ - `all()` and `any()` require dimensionless input and raise `TypeError` for physical units.
420
+ - `power()` requires a dimensionless exponent.
421
+ - `prod()` changes the unit exponent according to the number of factors; it is not interchangeable with additive reductions.
422
+ - `where(condition, x, y)` requires `x`, `y`, and `condition` to be broadcastable; use unit-compatible branches such as `a` and `0 * u.meter`.
423
+ - `searchsorted()` converts quantity `v` to the unit of quantity `a` before searching.
424
+ - `isclose()` and `allclose()` return booleans, not quantities; use a dimension-compatible absolute tolerance.
425
+ - Exact generated signatures include `**kwargs` for backend forwarding. Pass only arguments documented by the active backend; arbitrary keyword values are not valid.
426
+
427
+ ## Sources mirrored
428
+
429
+ - https://brainunit.readthedocs.io/apis/brainunit.math.html
430
+ - https://brainunit.readthedocs.io/unit_operations/einstein_operations.html
431
+ - Generated Level A pages under `https://brainunit.readthedocs.io/apis/generated/brainunit.math.<function>.html`
432
+ - https://brainunit.readthedocs.io/apis/generated/brainunit.math.einreduce.html
433
+ - https://brainunit.readthedocs.io/apis/generated/brainunit.math.einsum.html