brainx-skill 1.0.3 → 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 (51) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +21 -63
  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 +2 -2
  42. package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
  43. /package/{bin → installation/bin}/brainx.js +0 -0
  44. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  45. /package/{lib → installation/lib}/bundle.js +0 -0
  46. /package/{lib → installation/lib}/cli.js +0 -0
  47. /package/{lib → installation/lib}/constants.js +0 -0
  48. /package/{lib → installation/lib}/hash.js +0 -0
  49. /package/{lib → installation/lib}/paths.js +0 -0
  50. /package/{lib → installation/lib}/prompts.js +0 -0
  51. /package/{lib → installation/lib}/receipt.js +0 -0
@@ -0,0 +1,287 @@
1
+ ---
2
+ name: brainunit
3
+ description: BrainUnit is the central physical-quantity infrastructure for BrainX modeling and simulation. Use this skill for dimensional safety, typing, conversion, unit-aware math, JAX transformations, and external-library boundaries involving voltage, current, time, conductance, capacitance, length, concentration, temperature, physical constants, unit errors, dimensional mismatches, or suspicious bare numbers.
4
+ ---
5
+
6
+ ## Purpose and boundary
7
+
8
+ Use BrainUnit to keep physical meaning attached to numerical values throughout scientific computations. Keep the canonical path here; open only the narrow reference needed for specialized constructors, array mechanics, function semantics, custom units, extended typing, prefixes, or constants.
9
+
10
+ ## Underlying design of brainunit
11
+
12
+ A `Quantity` stores a numerical `mantissa` and a `unit`; the unit's conversion magnitude is `unit.factor * unit.base ** unit.scale`, so the numerical scaling of the represented value follows `mantissa * unit.factor * unit.base ** unit.scale`, while `unit.dim` supplies its physical dimension. Prefix-only units normally have a factor of one, so `5 * u.ms` corresponds to `5 * 1 * 10**-3 * u.second = 0.005 * u.second`. Use this model to diagnose prefix, scale, factor, or conversion behavior.
13
+
14
+ Note: This is underlying knowledge, not the ordinary user-facing coding model. In normal code, keep quantities intact and use public unit arithmetic and conversion APIs instead of manipulating `.mantissa`, `unit.factor`, `unit.base`, or `unit.scale` directly.
15
+
16
+ ## Relations between quantity, unit, and dimension
17
+
18
+ | Concept | Meaning | Example for `20 * u.ms` |
19
+ | --- | --- | --- |
20
+ | **Quantity** | The complete physical value | `20 ms` |
21
+ | **Unit** | The measurement scale used to express it | `ms` |
22
+ | **Dimension** | The physical category or structure | time (`T`) |
23
+
24
+ A `Dimension` describes the physical kind of a value. Internally, it is an immutable tuple of exponents over the seven SI base dimensions. A `Unit` is a particular measurement scale for a dimension. A `Quantity` combines a numerical value with a unit.
25
+
26
+ A quantity therefore inherits its dimension from its unit. For example, meters and kilometers are different units with different scales, but both have the dimension of length, so they can be converted into each other. Meters and seconds have different dimensions, so they are not convertible.
27
+
28
+ ## Relations between saiunit and brainunit
29
+
30
+ `saiunit` is the general scientific-computing implementation and can dispatch quantity mantissas across supported backends such as NumPy, JAX, CuPy, PyTorch, Dask, and ndonnx. `brainunit` is the neuroscience-facing namespace tailored to brain dynamics and the JAX-centered BrainX ecosystem; since BrainUnit's integration into SaiUnit, it reimports SaiUnit data structures and functions. Use only `brainunit` for BrainX and brain-modeling code.
31
+
32
+ ## Other core concepts
33
+
34
+ - `brainunit` provides physical units and a unit-aware mathematical system for BrainX brain-dynamics workflows, with JAX integration for transformations and accelerated execution.
35
+ - BrainUnit combines unit names with prefixes and appends a number for predefined squared and cubed forms. Examples include `msiemens`, `siemens2`, and `usiemens3`. Import `brainunit as u` instead of guessing a name or case-sensitive prefix.
36
+
37
+ ### Common neuroscience units
38
+
39
+ Use BrainUnit's predefined unit objects instead of bare scaling factors:
40
+
41
+ - Time: `u.second`, `u.ms`, `u.us`.
42
+ - Voltage: `u.volt`, `u.mV`.
43
+ - Current: `u.amp`, `u.mA`, `u.uA`, `u.nA`, `u.pA`.
44
+ - Conductance: `u.siemens`, `u.mS`, `u.uS`, `u.nS`.
45
+ - Capacitance: `u.farad`, `u.uF`, `u.nF`, `u.pF`.
46
+ - Resistance: `u.ohm`, `u.kohm`, `u.Mohm`.
47
+ - Frequency: `u.Hz`, `u.kHz`.
48
+
49
+ ## Brainunit API modules
50
+
51
+ | Module | Primary responsibility |
52
+ | --- | --- |
53
+ | `brainunit` | Top-level access to `Quantity`, `Unit`, `Dimension`, mismatch errors, compatibility checks, validation decorators, backend selection, temperature conversion, and custom-array integration. |
54
+ | `brainunit.typing` | `QuantityLike`, `UnitLike`, `DimensionLike`, runtime-checkable physical types and aliases, and `validate_units` for annotation-driven call validation. |
55
+ | `brainunit.autograd` | Unit-aware `grad`, `value_and_grad`, `vector_grad`, Jacobian transforms, and Hessians whose result units follow the differentiated function and arguments. |
56
+ | `brainunit.math` | Unit-aware array creation, activations, Einstein operations, and NumPy-style mathematics grouped by whether functions require unitless input, keep units, change units, or remove units. |
57
+ | `brainunit.linalg` | Unit-aware matrix products, decompositions, solvers, and norms, with explicit semantics for operations that keep, change, or remove units. |
58
+ | `brainunit.lax` | Low-level `jax.lax` wrappers for unit-aware array creation, elementwise operations, slicing, scattering, convolution, and linear algebra. |
59
+ | `brainunit.fft` | Unit-aware FFT, inverse FFT, frequency-bin, and shift operations that preserve or derive units according to the transform. |
60
+ | `brainunit.sparse` | Unit-bearing `SparseMatrix`, `CSR`, `CSC`, and `COO` structures plus dense-to-sparse, sparse-to-dense, and format-conversion operations. |
61
+ | `brainunit.constants` | Predefined physical constants as quantities with canonical values, dimensions, and units instead of bare numbers. |
62
+
63
+ ## Canonical imports
64
+
65
+ Use these imports for the bundled patterns below.
66
+
67
+ ```python
68
+ import brainunit as u
69
+ import jax
70
+ import jax.numpy as jnp
71
+ import numpy as np
72
+ ```
73
+
74
+ ## Create quantities
75
+
76
+ A `Quantity` is a numeric value plus a physical unit. Attach units at creation and retain them through code.
77
+
78
+ ```python
79
+ # Scalars and derived units.
80
+ speed = 10.0 * u.meter / u.second
81
+ # 10. m / s
82
+
83
+ # JAX array via multiplication shorthand.
84
+ jax_voltages = jnp.array([1.0, 2.5, 3.7]) * u.mV
85
+ # [1. 2.5 3.70000005] mV
86
+
87
+ # NumPy array via direct construction.
88
+ numpy_currents = u.Quantity(np.array([0.1, 0.2, 0.3]), unit=u.nA)
89
+ # [0.1 0.2 0.3] nA
90
+
91
+ # A string is accepted as the unit argument and parsed as a Unit.
92
+ string_unit_voltages = u.Quantity([1.0, 2.5, 3.7], "mV")
93
+ # [1. 2.5 3.7] mV
94
+ ```
95
+
96
+ Direct JAX and NumPy array mantissas retain their respective backends. In the string form, only the unit is a string; the mantissa must remain numeric.
97
+
98
+ ## Inspect quantities
99
+
100
+ Inspect quantity metadata without discarding its physical meaning.
101
+
102
+ ```python
103
+ q = jnp.array([[1.0, 2.0], [3.0, 4.0]]) * u.volt
104
+ print(q.mantissa, q.unit, q.dim, q.shape, q.dtype)
105
+ # Expected: numeric 2x2 mantissa, volt unit/dimension, shape (2, 2); dtype follows JAX configuration.
106
+ ```
107
+
108
+ Do not infer a unit from a parameter name. Inspect `.unit` and `.dim` when debugging; `.mantissa` exposes the current stored scale without converting it.
109
+
110
+ ## Compute with dimensions
111
+
112
+ BrainUnit represents units through seven irreducible SI dimensions: length, mass, time, electric current, temperature, amount of substance, and luminous intensity. Units are tracked automatically: addition and subtraction require matching dimensions and align compatible scales, while multiplication, division, powers, and supported functions combine dimension exponents. Treat an incompatibility as a model error rather than stripping units.
113
+
114
+ ```python
115
+ t1 = 500.0 * u.ms
116
+ t2 = 1.5 * u.second
117
+ elapsed = t1 + t2
118
+ # 2000. ms
119
+
120
+ work = (10.0 * u.newton) * (3.0 * u.meter)
121
+ # 30. J
122
+ average_speed = (100.0 * u.meter) / (10.0 * u.second)
123
+ # 10. m / s
124
+
125
+ try:
126
+ invalid = 5.0 * u.meter + 3.0 * u.second
127
+ except Exception as error:
128
+ print("dimension error:", error)
129
+ # Expected: prints a dimension-mismatch error
130
+ ```
131
+
132
+ ## Convert at explicit boundaries
133
+
134
+ Unit conversion changes the mantissa and unit used to represent a value, but it does not change the underlying physical quantity.
135
+
136
+ Use `in_unit(target)` to rescale while retaining a `Quantity`. Use `to_decimal(target)` only when an external API requires raw numbers, and make its expected unit explicit in the variable or parameter name.
137
+
138
+ ```python
139
+ distance = 2.5 * u.kmeter
140
+ distance_m = distance.in_unit(u.meter)
141
+ # 2500. m
142
+ distance_m_raw = distance.to_decimal(u.meter)
143
+ # 2500.0
144
+ ```
145
+
146
+ Do not substitute `.mantissa` for conversion.
147
+
148
+ ## Unit-aware math
149
+
150
+ Use `u.math` where unit semantics matter: functions may preserve units, change them, require dimensionless input, or return indices or booleans.
151
+
152
+ ```python
153
+ data = jnp.array([2.0, 4.0, 6.0, 8.0, 10.0]) * u.newton
154
+ total = u.math.sum(data)
155
+ # 30. N
156
+ mean = u.math.mean(data)
157
+ # 6. N
158
+ length = u.math.sqrt(4.0 * u.meter2)
159
+ # 2. m
160
+ ordered = u.math.sort(jnp.array([3.0, 1.0, 2.0]) * u.volt)
161
+ # [1. 2. 3.] V
162
+ ```
163
+
164
+ ## Constants
165
+
166
+ Do not confuse a unit constant with a quantity constant. A unit constant such as `u.minute` is a `Unit`: it defines a dimension and conversion scale but has no mantissa or physical amount until combined with a number. A value from `brainunit.constants` such as `u.constants.minute` or `u.constants.boltzmann` is already a `Quantity` with both a numerical mantissa and a unit.
167
+
168
+ ```python
169
+ minute_unit = u.minute
170
+ assert isinstance(minute_unit, u.Unit)
171
+
172
+ one_minute = u.constants.minute
173
+ assert isinstance(one_minute, u.Quantity)
174
+ # 60. s
175
+
176
+ five_minutes = 5 * minute_unit
177
+ # 5. min
178
+
179
+ avogadro = u.constants.avogadro
180
+ # 6.02214076e+23 1 / mol
181
+ boltzmann = u.constants.boltzmann
182
+ # 1.380649e-23 J / K
183
+ elementary_charge = u.constants.elementary_charge
184
+ # 1.60217663e-19 C
185
+ ```
186
+
187
+ ## Normalize inputs and create ranges
188
+
189
+ Use `u.math.asarray()` to normalize plain data and quantities. Without `unit`, it returns an array for plain data or preserves the input unit; with `unit=target`, it returns a `Quantity` converted to `target`. Incompatible quantity inputs raise `UnitMismatchError`. `u.math.array` is an alias.
190
+
191
+ Use `u.math.arange()` to create half-open intervals `[start, stop)`, returning an array for plain arguments or a `Quantity` for unit-bearing arguments. Unit-bearing `start`, `stop`, and `step` must share one unit. At least one of `start` or `stop` is required.
192
+
193
+ ```python
194
+ plain = u.math.asarray([1, 2, 3])
195
+ # Array([1, 2, 3], dtype=int32)
196
+ inferred = u.math.asarray([1 * u.second, 2 * u.second])
197
+ # Expected: a Quantity with mantissa [1, 2] and unit second.
198
+ seconds = u.math.asarray([1000 * u.ms, 2000 * u.ms], unit=u.second)
199
+ # Quantity([1. 2.], "s")
200
+
201
+ indices = u.math.arange(5)
202
+ # Array([0, 1, 2, 3, 4], dtype=int32)
203
+ times = u.math.arange(0.0 * u.ms, 10.0 * u.ms, 0.1 * u.ms)
204
+ # Expected: 100 values from 0.0 through 9.9 ms; array precision follows JAX.
205
+ ```
206
+
207
+ Do not strip units before normalization or attach a unit to an unchecked plain range afterward.
208
+
209
+ ## Type and validate quantity boundaries
210
+
211
+ BrainUnit typing expresses whether an interface accepts convertible values, a particular unit dimension, or a named physical type. `QuantityLike` includes plain numbers, NumPy/JAX arrays, and existing quantities; it does not itself require a unit. `UnitLike` accepts a `Unit`, a unit string, or `None`. Use `u.Quantity[unit]` for a unit-derived dimension and `u.Quantity["physical type"]` for a named dimension.
212
+
213
+ Annotations alone describe the contract. Apply `@u.typing.validate_units` when calls must be checked at runtime; by default it accepts dimensionally compatible scales, while `strict=True` requires an exact unit for unit-based annotations.
214
+
215
+ ```python
216
+ def normalize(values: u.typing.QuantityLike, unit: u.typing.UnitLike = None):
217
+ return u.math.asarray(values, unit=unit)
218
+
219
+
220
+ @u.typing.validate_units
221
+ def travel_time(
222
+ distance: u.Quantity["length"],
223
+ speed: u.Quantity["speed"],
224
+ ) -> u.Quantity["time"]:
225
+ return distance / speed
226
+
227
+
228
+ duration = travel_time(100.0 * u.meter, 5.0 * u.meter / u.second)
229
+ # Expected: 20 seconds.
230
+ ```
231
+
232
+ Use `@u.typing.validate_units` when `Quantity[...]` annotations define the runtime contract. Open the typing reference for additional aliases, runtime type helpers, and strict-validation details.
233
+
234
+ If `brainunit.typing` is unavailable, upgrade BrainUnit with its matched SaiUnit dependency; do not mix validators and `Quantity` types from different releases.
235
+
236
+ ## Unit aware transformation
237
+
238
+ BrainUnit quantities work with JAX transformations such as `jax.jit` and `jax.vmap`; units are tracked through compilation, and these transformations compose with BrainUnit automatic differentiation.
239
+
240
+ `u.autograd.grad` is BrainUnit's physical-unit-aware version of `jax.grad`: for a scalar-valued function with quantity arguments, it automatically returns derivatives with the correct unit, `unit(output) / unit(input)`. Raw `jax.grad` does not reconstruct derivative units, while `brainstate.transform.grad` is primarily state-aware and requires `unit_aware=True` for unit-aware gradients.
241
+
242
+ ```python
243
+ @jax.jit
244
+ def kinetic_energy(m, v):
245
+ return 0.5 * m * v**2
246
+
247
+
248
+ energy = kinetic_energy(2.0 * u.kilogram, 3.0 * u.meter / u.second)
249
+ # 9. J
250
+ velocities = jnp.array([1.0, 2.0, 3.0, 4.0, 5.0]) * u.meter / u.second
251
+ energies = jax.vmap(lambda v: kinetic_energy(2.0 * u.kilogram, v))(velocities)
252
+ # [ 1. 4. 9. 16. 25.] J
253
+
254
+ denergy_dv = u.autograd.grad(
255
+ lambda v: 0.5 * (2.0 * u.kilogram) * v**2
256
+ )
257
+ momentum = denergy_dv(3.0 * u.meter / u.second)
258
+ # 6. kg * m / s
259
+ ```
260
+
261
+ ## Convert Celsius at affine boundaries
262
+
263
+ BrainUnit stores temperature quantities in kelvin. `u.celsius2kelvin(x)` accepts a plain scalar or array and returns a kelvin `Quantity` using `K = C + 273.15`; `u.kelvin2celsius(q)` requires a temperature `Quantity` and returns a plain scalar or array using `C = K - 273.15`.
264
+
265
+ ```python
266
+ kelvin = u.celsius2kelvin(jnp.array([0.0, 25.0]))
267
+ # Expected: [273.15, 298.15] K; array precision follows JAX.
268
+ celsius = u.kelvin2celsius(kelvin)
269
+ # Expected: a plain array [0.0, 25.0], subject to floating-point precision.
270
+ delta_t = 10.0 * u.kelvin
271
+ # 10. K
272
+ ```
273
+
274
+ The first function rejects quantities, and the second rejects plain or non-temperature inputs. Apply the Celsius offset only to absolute temperatures, not differences; `u.constants.zero_celsius` is the explicit `273.15 K` offset for formulas that need it.
275
+
276
+ ## Reference routing
277
+
278
+ | Reference | Open when |
279
+ |---|---|
280
+ | `references/quantity-inspection-and-conversion.md` | Inspecting compatibility, dimensions, conversions, decomposition, formatting, or raw-value boundaries beyond the canonical pattern. |
281
+ | `references/array-creation.md` | Creating specialized ranges, grids, filled or template-shaped arrays, matrices, triangular indices, or tree-shaped arrays beyond `asarray` and `arange`. |
282
+ | `references/array-mechanics.md` | Indexing, functional updates, reshaping, broadcasting, joining, splitting, repeating, backend conversion, or named-axis rearrangement. |
283
+ | `references/math-function-library.md` | Selecting functions by dimensionless-input, unit-preserving, unit-changing, reduction, contraction, comparison, boolean, or index-returning semantics. |
284
+ | `references/unit-structure-and-definition.md` | Inspecting unit structure, comparing scale and dimension, composing units, or defining named, derived, or scaled custom units. |
285
+ | `references/typing-and-runtime-validation.md` | Selecting core type aliases, physical-type aliases, runtime type helpers, or strict annotation-driven validation. |
286
+ | `references/prefix-library.md` | Looking up predefined SI base or derived units, generated unit names, prefix symbols, and prefix scales. |
287
+ | `references/physical-constant-library.md` | Looking up predefined constant names, values, dimensions, and canonical units. |
@@ -0,0 +1,158 @@
1
+ # Array creation
2
+
3
+ Use this reference for specialized unit-aware ranges, grids, filled arrays, template-shaped arrays, matrix patterns, index constructors, and tree-shaped arrays. Basic `Quantity`, `asarray()`, and `arange()` construction remains in the parent skill.
4
+
5
+ ```python
6
+ import brainunit as u
7
+ import jax.numpy as jnp
8
+ ```
9
+
10
+ ## Contents
11
+
12
+ - [Choose interval values](#choose-interval-values)
13
+ - [Build coordinate and power grids](#build-coordinate-and-power-grids)
14
+ - [Fill a new shape](#fill-a-new-shape)
15
+ - [Follow an existing shape](#follow-an-existing-shape)
16
+ - [Build matrices and masks](#build-matrices-and-masks)
17
+ - [Locate triangular entries](#locate-triangular-entries)
18
+ - [Mirror pytrees](#mirror-pytrees)
19
+ - [Convert NumPy input](#convert-numpy-input)
20
+ - [Routing](#routing)
21
+ - [Cross-family gotchas](#cross-family-gotchas)
22
+ - [Sources mirrored](#sources-mirrored)
23
+
24
+ ## Choose interval values
25
+
26
+ ### `linspace`
27
+
28
+ | Exact signature | Use when | One-line description | Code and result |
29
+ |---|---|---|---|
30
+ | `linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)` | Generate a fixed number of evenly spaced samples between two endpoints. | Return evenly spaced numbers over a specified interval. | `u.math.linspace(0 * u.second, 10 * u.second, 5)`<br>`# Quantity([ 0. 2.5 5. 7.5 10. ], "s")` |
31
+
32
+ ### `logspace`
33
+
34
+ | Exact signature | Use when | One-line description | Code and result |
35
+ |---|---|---|---|
36
+ | `logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)` | Generate values whose exponents are evenly spaced. | Return numbers spaced evenly on a log scale. | `u.math.logspace(0, 2, 3)`<br>`# Array([ 1., 10., 100.], dtype=float32)` |
37
+
38
+ ## Build coordinate and power grids
39
+
40
+ ### `meshgrid`
41
+
42
+ | Exact signature | Use when | One-line description | Code and result |
43
+ |---|---|---|---|
44
+ | `meshgrid(*xi, copy=True, sparse=False, indexing='xy')` | Expand 1-D coordinate vectors into dense or sparse coordinate grids. | Return coordinate matrices from coordinate vectors. | `x = jnp.array([1, 2]) * u.meter; t = jnp.array([0, 1, 2]) * u.second; x_grid, t_grid = u.math.meshgrid(x, t, indexing='ij')`<br>`# both shapes: (2, 3); units: meter and second` |
45
+
46
+ ### `vander`
47
+
48
+ | Exact signature | Use when | One-line description | Code and result |
49
+ |---|---|---|---|
50
+ | `vander(x, N=None, increasing=False, unit=Unit('1'))` | Build a Vandermonde matrix from powers of a 1-D vector. | Generate a Vandermonde matrix. | `u.math.vander(jnp.array([1, 2]), N=3)`<br>`# Array([[1, 1, 1], [4, 2, 1]], dtype=int32)` |
51
+
52
+ ## Fill a new shape
53
+
54
+ ### Initialized arrays
55
+
56
+ | API | Description & result |
57
+ |---|---|
58
+ | `full(shape, fill_value, dtype=None)` | Fill a new shape with `fill_value`; a quantity fill produces a `Quantity` with that unit.<br>`u.math.full(2, 3 * u.second)`<br>`# Quantity([3, 3], "s")` |
59
+ | `ones(shape, dtype=None, unit=Unit('1'))` | Fill a new shape with ones. Returns a plain JAX array by default or a `Quantity` when a non-trivial unit is supplied.<br>`u.math.ones(2, unit=u.second)`<br>`# Quantity([1., 1.], "s")` |
60
+ | `zeros(shape, dtype=None, unit=Unit('1'))` | Fill a new shape with zeros. Returns a plain JAX array by default or a `Quantity` when a non-trivial unit is supplied.<br>`u.math.zeros(2)`<br>`# plain JAX array` |
61
+
62
+ ### `empty`
63
+
64
+ | Exact signature | Use when | One-line description | Code and result |
65
+ |---|---|---|---|
66
+ | `empty(shape, dtype=None, unit=Unit('1'))` | Allocate a shape when every entry will be overwritten before it is read. | Return a new quantity or array of given shape and type, without initializing entries. | `buffer = u.math.empty((2, 2), unit=u.second); buffer.shape`<br>`# (2, 2); entry values are unspecified` |
67
+
68
+ ## Follow an existing shape
69
+
70
+ ### `full_like`
71
+
72
+ | Exact signature | Use when | One-line description | Code and result |
73
+ |---|---|---|---|
74
+ | `full_like(a, fill_value, dtype=None, shape=None)` | Fill an array using a prototype's shape and dtype. | Return a new quantity or array with the same shape and type as a given array or quantity, filled with `fill_value`. | `prototype = jnp.zeros(2) * u.second; u.math.full_like(prototype, 500 * u.ms)`<br>`# Quantity([0.5 0.5], "s")` |
75
+
76
+ ### `empty_like`
77
+
78
+ | Exact signature | Use when | One-line description | Code and result |
79
+ |---|---|---|---|
80
+ | `empty_like(prototype, dtype=None, shape=None, unit=Unit('1'))` | Allocate an uninitialized buffer shaped and typed like a prototype. | Return a new quantity or array with the same shape and type as a given array. | `prototype = jnp.ones(3) * u.second; buffer = u.math.empty_like(prototype); buffer.shape`<br>`# (3,); unit: second; entry values are unspecified` |
81
+
82
+ ### Create one or zero arrays
83
+
84
+ | API | Description & result |
85
+ |---|---|
86
+ | `ones_like(a, dtype=None, shape=None, unit=Unit('1'))` | Create ones with `a`'s shape and dtype. A `Quantity` prototype preserves its unit by default; a non-trivial `unit` attaches a unit to a plain prototype or requests a compatible conversion. |
87
+ | `zeros_like(a, dtype=None, shape=None, unit=Unit('1'))` | Create zeros with `a`'s shape and dtype. A `Quantity` prototype preserves its unit by default; a non-trivial `unit` attaches a unit to a plain prototype or requests a compatible conversion. |
88
+
89
+ ## Build matrices and masks
90
+
91
+ ### Identity-like and triangular constructors
92
+
93
+ | API | Description & result |
94
+ |---|---|
95
+ | `eye(N, M=None, k=0, dtype=None, unit=Unit('1'))` | Create an `N`-by-`M` array with ones on diagonal `k` and zeros elsewhere. Returns a plain JAX array by default or a `Quantity` with a non-trivial unit. |
96
+ | `identity(n, dtype=None, unit=Unit('1'))` | Create an `n`-by-`n` identity array. Returns a plain JAX array by default or a `Quantity` with a non-trivial unit. |
97
+ | `tri(N, M=None, k=0, dtype=None, unit=Unit('1'))` | Create an `N`-by-`M` array with ones at and below diagonal `k`. Returns a plain JAX array by default or a `Quantity` with a non-trivial unit. |
98
+
99
+ ### `diag`
100
+
101
+ | Exact signature | Use when | One-line description | Code and result |
102
+ |---|---|---|---|
103
+ | `diag(v, k=0, unit=Unit('1'))` | Construct a diagonal matrix or extract a diagonal based on input rank. | Extract a diagonal or construct a diagonal array. | `vector = jnp.array([1, 2, 3]) * u.second; matrix = u.math.diag(vector); extracted = u.math.diag(matrix); (matrix.shape, extracted.shape)`<br>`# ((3, 3), (3,))` |
104
+
105
+ ### Keep one triangle of an existing array
106
+
107
+ | API | Description & result |
108
+ |---|---|
109
+ | `tril(m, k=0, unit=Unit('1'))` | Return `m` with entries above diagonal `k` zeroed, applying to the final two axes when `m.ndim > 2`. It preserves a `Quantity` input's unit by default; `unit` can attach or request a compatible output unit.<br>`m = jnp.arange(1, 5).reshape(2, 2); u.math.tril(m)`<br>`# [[1, 0], [3, 4]]` |
110
+ | `triu(m, k=0, unit=Unit('1'))` | Return `m` with entries below diagonal `k` zeroed, applying to the final two axes when `m.ndim > 2`. It preserves a `Quantity` input's unit by default; `unit` can attach or request a compatible output unit.<br>`m = jnp.arange(1, 5).reshape(2, 2); u.math.triu(m)`<br>`# [[1, 2], [0, 4]]` |
111
+
112
+ ### `fill_diagonal`
113
+
114
+ | Exact signature | Use when | One-line description | Code and result |
115
+ |---|---|---|---|
116
+ | `fill_diagonal(a, val, wrap=False, inplace=False)` | Replace the main diagonal of an existing array with one value. | Fill the main diagonal of the given array of any dimensionality. | `q = jnp.zeros((2, 2)) * u.second; filled = u.math.fill_diagonal(q, 500 * u.ms)`<br>`# Quantity([[0.5 0. ] [0. 0.5]], "s")` |
117
+
118
+ ## Locate triangular entries
119
+
120
+ ### Lower and upper triangle indices
121
+
122
+ | API | Description & result |
123
+ |---|---|
124
+ | `tril_indices(n, k=0, m=None)` | Return row and column indices for the lower triangle of an `(n, m)` array as two plain integer arrays. |
125
+ | `triu_indices(n, k=0, m=None)` | Return row and column indices for the upper triangle of an `(n, m)` array as two plain integer arrays. |
126
+ | `tril_indices_from(arr, k=0)` | Derive lower-triangle row and column indices from a 2-D array's shape. Returns two plain integer arrays; an input `Quantity` does not give the indices a unit. |
127
+ | `triu_indices_from(arr, k=0)` | Derive upper-triangle row and column indices from a 2-D array's shape. Returns two plain integer arrays; an input `Quantity` does not give the indices a unit. |
128
+
129
+ ## Mirror pytrees
130
+
131
+ ### One or zero in every leaf
132
+
133
+ | API | Description & result |
134
+ |---|---|
135
+ | `tree_ones_like(tree)` | Replace every pytree leaf with ones while preserving structure, leaf shape, dtype, and unit; plain leaves remain plain and quantity leaves remain quantities. |
136
+ | `tree_zeros_like(tree)` | Replace every pytree leaf with zeros while preserving structure, leaf shape, dtype, and unit; plain leaves remain plain and quantity leaves remain quantities. |
137
+
138
+ ## Convert NumPy input
139
+
140
+ | API | Description & result |
141
+ |---|---|
142
+ | `from_numpy(x, unit=Unit('1'))` | Convert a NumPy array to the JAX backend. Returns a plain JAX array by default or a `Quantity` with the supplied non-trivial unit. |
143
+
144
+ ## Routing
145
+
146
+ `array_split()` appears on the tutorial page, but it is a structural operation; route it to `array-mechanics.md`.
147
+
148
+ Backend extraction and `as_numpy()` belong in `array-mechanics.md` because they cross an existing array boundary rather than create a scientific quantity from source values.
149
+
150
+ ## Cross-family gotchas
151
+
152
+ - For constructors with `unit=Unit('1')`, the unitless default produces a plain JAX array unless a quantity input supplies a unit; pass a non-trivial `Unit` to request a `Quantity`.
153
+ - The `dtype` and `shape` arguments on `*_like` functions override the prototype; otherwise its dtype and shape are retained.
154
+
155
+ ## Sources mirrored
156
+
157
+ - https://brainx.chaobrain.com/brainunit/unit_operations/array_creation.html
158
+ - https://brainx.chaobrain.com/brainunit/apis/brainunit.math.html
@@ -0,0 +1,90 @@
1
+ # Functional structural API
2
+
3
+ Open this second-level reference from `../array-mechanics.md` when selecting a `brainunit.math` function for joining, stacking, splitting, broadcasting, reshaping, repeating, or selecting values. The module API categorizes these as functions that keep units.
4
+
5
+ ```python
6
+ import brainunit as u
7
+ import jax.numpy as jnp
8
+ ```
9
+
10
+ Examples use concise `Quantity(..., "unit")` results; the exact displayed representation can vary by backend and BrainUnit version.
11
+
12
+ ## Contents
13
+
14
+ - [Joining and stacking](#joining-and-stacking)
15
+ - [Splitting](#splitting)
16
+ - [Minimum rank and broadcasting](#minimum-rank-and-broadcasting)
17
+ - [Shape and axis operations](#shape-and-axis-operations)
18
+ - [Repetition](#repetition)
19
+ - [Selection](#selection)
20
+
21
+ ## Joining and stacking
22
+
23
+ | Exact signature | One-line description | Example & result |
24
+ |---|---|---|
25
+ | `concatenate(arrays, axis=0, dtype=None, **kwargs)` | Join a sequence of quantities or arrays along an existing axis. | `a = [1, 2] * u.second; b = [3, 4] * u.second; u.math.concatenate([a, b])`<br>`# Quantity([1 2 3 4], "s")` |
26
+ | `stack(arrays, axis=0, dtype=None, **kwargs)` | Join a sequence of quantities or arrays along a new axis. | `a = [1, 2, 3] * u.second; b = [4, 5, 6] * u.second; u.math.stack([a, b])`<br>`# Quantity([[1 2 3] [4 5 6]], "s")` |
27
+ | `block(arrays, **kwargs)` | Assemble a quantity or an array from nested lists of blocks. | `a = [[1, 2], [3, 4]] * u.second; u.math.block(a)`<br>`# Quantity([[1 2] [3 4]], "s")` |
28
+ | `append(arr, values, axis=None, **kwargs)` | Append values to the end of a quantity or an array. | `a = [1, 2, 3] * u.second; u.math.append(a, 4 * u.second)`<br>`# Quantity([1 2 3 4], "s")` |
29
+ | `row_stack(tup, dtype=None, **kwargs)` | Stack quantities or arrays in sequence vertically (row wise). | `a = [1, 2, 3] * u.meter; b = [4, 5, 6] * u.meter; u.math.row_stack([a, b])`<br>`# Quantity([[1 2 3] [4 5 6]], "m")` |
30
+ | `vstack(tup, dtype=None, **kwargs)` | Stack quantities or arrays in sequence vertically (row wise). | `a = [1, 2, 3] * u.meter; b = [4, 5, 6] * u.meter; u.math.vstack([a, b])`<br>`# Quantity([[1 2 3] [4 5 6]], "m")` |
31
+ | `hstack(arrays, dtype=None, **kwargs)` | Stack quantities or arrays in sequence horizontally (column wise). | `a = [1, 2, 3] * u.meter; b = [4, 5, 6] * u.meter; u.math.hstack([a, b])`<br>`# Quantity([1 2 3 4 5 6], "m")` |
32
+ | `dstack(arrays, dtype=None, **kwargs)` | Stack quantities or arrays in sequence depth wise (along the third axis). | `a = [[1], [2], [3]] * u.meter; b = [[4], [5], [6]] * u.meter; u.math.dstack([a, b])`<br>`# Quantity([[[1 4]] [[2 5]] [[3 6]]], "m")` |
33
+ | `column_stack(tup, **kwargs)` | Stack 1-D arrays as columns into a 2-D array. | `a = [1, 2, 3] * u.second; b = [4, 5, 6] * u.second; u.math.column_stack([a, b])`<br>`# Quantity([[1 4] [2 5] [3 6]], "s")` |
34
+
35
+ `row_stack` is documented as an alias of `vstack`; its callable signature therefore mirrors `vstack`.
36
+
37
+ ## Splitting
38
+
39
+ | Exact signature | One-line description | Example & result |
40
+ |---|---|---|
41
+ | `split(a, indices_or_sections, axis=0, **kwargs)` | Split a quantity or array into a list of multiple sub-arrays. | `a = jnp.arange(9.0) * u.second; u.math.split(a, 3)`<br>`# [Quantity([0. 1. 2.], "s"), Quantity([3. 4. 5.], "s"), Quantity([6. 7. 8.], "s")]` |
42
+ | `array_split(ary, indices_or_sections, axis=0, **kwargs)` | Split an array into multiple sub-arrays. | `a = jnp.arange(9.0) * u.second; parts = u.math.array_split(a, 3); [x.shape for x in parts]`<br>`# [(3,), (3,), (3,)]` |
43
+ | `dsplit(a, indices_or_sections, **kwargs)` | Split a quantity or an array into multiple sub-arrays along the third axis (depth). | `a = jnp.arange(16.0).reshape(2, 2, 4) * u.meter; parts = u.math.dsplit(a, 2); [x.shape for x in parts]`<br>`# [(2, 2, 2), (2, 2, 2)]` |
44
+ | `hsplit(a, indices_or_sections, **kwargs)` | Split a quantity or an array into multiple sub-arrays horizontally (column-wise). | `a = jnp.arange(16.0).reshape(4, 4) * u.meter; parts = u.math.hsplit(a, 2); [x.shape for x in parts]`<br>`# [(4, 2), (4, 2)]` |
45
+ | `vsplit(a, indices_or_sections, **kwargs)` | Split a quantity or an array into multiple sub-arrays vertically (row-wise). | `a = jnp.arange(16.0).reshape(4, 4) * u.meter; parts = u.math.vsplit(a, 2); [x.shape for x in parts]`<br>`# [(2, 4), (2, 4)]` |
46
+
47
+ ## Minimum rank and broadcasting
48
+
49
+ | Exact signature | One-line description | Example & result |
50
+ |---|---|---|
51
+ | `atleast_1d(*arys, **kwargs)` | View inputs as quantities or arrays with at least one dimension. | `u.math.atleast_1d(0 * u.second)`<br>`# Quantity([0], "s")` |
52
+ | `atleast_2d(*arys, **kwargs)` | View inputs as quantities or arrays with at least two dimensions. | `a = [1, 2, 3] * u.second; u.math.atleast_2d(a)`<br>`# Quantity([[1 2 3]], "s")` |
53
+ | `atleast_3d(*arys, **kwargs)` | View inputs as quantities or arrays with at least three dimensions. | `a = [[1, 2], [3, 4]] * u.meter; u.math.atleast_3d(a).shape`<br>`# (2, 2, 1)` |
54
+ | `broadcast_arrays(*args, **kwargs)` | Broadcast any number of arrays against each other. | `a = [1, 2, 3] * u.second; b = [[4], [5]] * u.second; result = u.math.broadcast_arrays(a, b); [x.shape for x in result]`<br>`# [(2, 3), (2, 3)]` |
55
+ | `broadcast_to(array, shape, **kwargs)` | Broadcast an array to a new shape. | `a = [1, 2, 3] * u.meter; u.math.broadcast_to(a, (2, 3))`<br>`# Quantity([[1 2 3] [1 2 3]], "m")` |
56
+
57
+ ## Shape and axis operations
58
+
59
+ | Exact signature | One-line description | Example & result |
60
+ |---|---|---|
61
+ | `reshape(a, shape, order='C', **kwargs)` | Gives a new shape to a quantity or an array without changing its data. | `a = [1, 2, 3, 4] * u.second; u.math.reshape(a, (2, 2))`<br>`# Quantity([[1 2] [3 4]], "s")` |
62
+ | `moveaxis(a, source, destination, **kwargs)` | Moves axes of a quantity or an array to new positions. | `a = jnp.zeros((3, 4, 5)) * u.meter; u.math.moveaxis(a, 0, -1).shape`<br>`# (4, 5, 3)` |
63
+ | `transpose(a, axes=None, **kwargs)` | Permute the dimensions of a quantity or an array. | `a = jnp.ones((2, 3)) * u.second; u.math.transpose(a).shape`<br>`# (3, 2)` |
64
+ | `swapaxes(a, axis1, axis2, **kwargs)` | Interchange two axes of a quantity or an array. | `a = jnp.zeros((3, 4, 5)) * u.meter; u.math.swapaxes(a, 0, 2).shape`<br>`# (5, 4, 3)` |
65
+ | `expand_dims(a, axis, **kwargs)` | Expand the shape of a quantity or an array. | `a = [1, 2, 3] * u.meter; u.math.expand_dims(a, axis=0).shape`<br>`# (1, 3)` |
66
+ | `squeeze(a, axis=None, **kwargs)` | Remove single-dimensional entries from the shape of a quantity or an array. | `a = [[[1], [2], [3]]] * u.second; u.math.squeeze(a).shape`<br>`# (3,)` |
67
+ | `flatten(x, start_axis=None, end_axis=None, **kwargs)` | Flattens input by reshaping it into a one-dimensional tensor. | `a = [[1, 2], [3, 4]] * u.second; u.math.flatten(a)`<br>`# Quantity([1 2 3 4], "s")` |
68
+ | `unflatten(x, axis, sizes, **kwargs)` | Expands a dimension of the input tensor over multiple dimensions. | `a = [1, 2, 3, 4, 5, 6] * u.meter; u.math.unflatten(a, 0, (2, 3))`<br>`# Quantity([[1 2 3] [4 5 6]], "m")` |
69
+
70
+ ## Repetition
71
+
72
+ | Exact signature | One-line description | Example & result |
73
+ |---|---|---|
74
+ | `tile(A, reps, **kwargs)` | Construct a quantity or an array by repeating `A` the number of times given by `reps`. | `a = [1, 2, 3] * u.meter; u.math.tile(a, 2)`<br>`# Quantity([1 2 3 1 2 3], "m")` |
75
+ | `repeat(a, repeats, axis=None, total_repeat_length=None, **kwargs)` | Repeat elements of a quantity or an array. | `a = [1, 2, 3] * u.second; u.math.repeat(a, 2)`<br>`# Quantity([1 1 2 2 3 3], "s")` |
76
+
77
+ ## Selection
78
+
79
+ | Exact signature | One-line description | Example & result |
80
+ |---|---|---|
81
+ | `take(a, indices, axis=None, mode=None, unique_indices=False, indices_are_sorted=False, fill_value=None, **kwargs)` | Take elements from an array along an axis. | `a = [4, 3, 5, 7, 6, 8] * u.second; u.math.take(a, jnp.array([0, 1, 4]))`<br>`# Quantity([4 3 6], "s")` |
82
+ | `gather(input, dim, index, **kwargs)` | Gather values along an axis specified by `dim`, according to `index`. | `a = jnp.array([[1, 2], [3, 4]]) * u.mV; index = jnp.array([[0, 0], [1, 0]]); u.math.gather(a, 1, index)`<br>`# Quantity([[1 1] [4 3]], "mV")` |
83
+ | `choose(a, choices, mode='raise', **kwargs)` | Construct a quantity or an array from an index array and a set of arrays to choose from. | `choices = [jnp.array([1, 2, 3]), jnp.array([4, 5, 6])]; u.math.choose(jnp.array([0, 1, 0]), choices)`<br>`# Array([1, 5, 3], dtype=int32)` |
84
+ | `compress(condition, a, axis=None, *, size=None, fill_value=None, **kwargs)` | Return selected slices of a quantity or an array along given axis. | `a = [1, 2, 3, 4] * u.meter; u.math.compress(jnp.array([0, 1, 1, 0]), a)`<br>`# Quantity([2 3], "m")` |
85
+ | `extract(condition, arr, *, size=None, fill_value=None, **kwargs)` | Return the elements of an array that satisfy some condition. | `a = jnp.array([1, 2, 3]) * u.meter; u.math.extract(a.mantissa > 1, a)`<br>`# Quantity([2 3], "m")` |
86
+
87
+ ## Sources mirrored
88
+
89
+ - https://brainunit.readthedocs.io/apis/brainunit.math.html
90
+ - Generated function pages linked from the module index: `https://brainunit.readthedocs.io/apis/generated/brainunit.math.<function>.html`