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,58 @@
1
+ # Physical constant library
2
+
3
+ Use this reference to select the exact predefined constant name, inspect its displayed unit, and avoid replacing a unit-aware constant with a bare numeric literal.
4
+
5
+ ## Import
6
+
7
+ ```python
8
+ from brainunit import constants
9
+ ```
10
+
11
+ Each listed object is displayed by the official page as a `Quantity`.
12
+
13
+ ## Constant lookup
14
+
15
+ | API | Official role | Displayed value and unit |
16
+ |---|---|---|
17
+ | `constants.avogadro` | Avogadro number | `Quantity(6.02214076e+23, "1 / mol")` |
18
+ | `constants.boltzmann` | Boltzmann constant | `Quantity(1.380649e-23, "J / K")` |
19
+ | `constants.electric` | Electric constant / vacuum permittivity | `Quantity(8.85418782e-12, "F / m")` |
20
+ | `constants.electron_mass` | Electron mass | `Quantity(9.10938371e-31, "kg")` |
21
+ | `constants.elementary_charge` | Elementary charge magnitude | `Quantity(1.60217663e-19, "C")` |
22
+ | `constants.faraday` | Faraday constant | `Quantity(96485.33212331, "C / mol")` |
23
+ | `constants.gas` | Universal gas constant | `Quantity(8.31446262, "J / (K * mol)")` |
24
+ | `constants.magnetic` | Magnetic constant / vacuum permeability | `Quantity(1.25663706e-06, "N / A^2")` |
25
+ | `constants.molar_mass` | Molar mass constant | `Quantity(0.001, "kg / mol")` |
26
+ | `constants.zero_celsius` | Zero Celsius expressed in kelvin | `Quantity(273.15, "K")` |
27
+
28
+ The values and units mirror the constants page. Use the constant object in calculations so BrainUnit retains its physical dimensions.
29
+
30
+ ## Selection cues
31
+
32
+ - Statistical mechanics energy per temperature: `constants.boltzmann`.
33
+ - Per-mole ideal-gas calculations: `constants.gas`.
34
+ - Particle count per mole: `constants.avogadro`.
35
+ - Charge per mole in electrochemistry: `constants.faraday`.
36
+ - Single elementary-charge magnitude: `constants.elementary_charge`.
37
+ - Electromagnetic vacuum properties: `constants.electric` and `constants.magnetic`.
38
+ - Celsius offset handling: `constants.zero_celsius`; see `Convert Celsius At Affine Boundaries` in the parent skill for the affine conversion functions.
39
+
40
+ ## Unit-aware use
41
+
42
+ ```python
43
+ import brainunit as u
44
+
45
+ R = u.constants.gas
46
+ # Quantity(8.31446262, "J / (K * mol)")
47
+ T = u.celsius2kelvin(25.0)
48
+ # 298.15 K
49
+ V = 0.0224 * u.meter**3
50
+ pressure = R * T / V
51
+ # Expected: approximately 110667.73 kg / (m * s^2 * mol).
52
+ ```
53
+
54
+ This reference is a lookup catalog. Physical-constant arithmetic and the basic constants workflow remain in the main skill.
55
+
56
+ ## Sources mirrored
57
+
58
+ - https://brainx.chaobrain.com/brainunit/physical_units/constants.html
@@ -0,0 +1,116 @@
1
+ # Prefix library
2
+
3
+ Use this reference to look up supported SI prefix symbols and scales, inspect the official base/derived unit spellings shown by the standard-units page, or create a prefixed custom unit.
4
+
5
+ ## Contents
6
+
7
+ - [Supported prefixes](#supported-prefixes)
8
+ - [Base-unit spelling lookup](#base-unit-spelling-lookup)
9
+ - [Derived-unit lookup](#derived-unit-lookup)
10
+ - [Creating scaled units](#creating-scaled-units)
11
+ - [Source-backed gotchas](#source-backed-gotchas)
12
+
13
+ ## Supported prefixes
14
+
15
+ | Symbol | Prefix | Value |
16
+ |---|---|---:|
17
+ | `Y` | yotta | `1e24` |
18
+ | `Z` | zetta | `1e21` |
19
+ | `E` | exa | `1e18` |
20
+ | `P` | peta | `1e15` |
21
+ | `T` | tera | `1e12` |
22
+ | `G` | giga | `1e9` |
23
+ | `M` | mega | `1e6` |
24
+ | `k` | kilo | `1e3` |
25
+ | `h` | hecto | `1e2` |
26
+ | `da` | deka/deca | `1e1` |
27
+ | `d` | deci | `1e-1` |
28
+ | `c` | centi | `1e-2` |
29
+ | `m` | milli | `1e-3` |
30
+ | `u` | micro | `1e-6` |
31
+ | `n` | nano | `1e-9` |
32
+ | `p` | pico | `1e-12` |
33
+ | `f` | femto | `1e-15` |
34
+ | `a` | atto | `1e-18` |
35
+ | `z` | zepto | `1e-21` |
36
+ | `y` | yocto | `1e-24` |
37
+
38
+ BrainUnit uses ASCII `u` for the micro prefix in API names and `create_scaled_unit()` calls.
39
+
40
+ ## Base-unit spelling lookup
41
+
42
+ The standard-units page creates these named objects:
43
+
44
+ | Local variable | `Unit.create()` name | Display symbol | Dimension key |
45
+ |---|---|---|---|
46
+ | `metre` | `"meter"` | `"m"` | `m=1` |
47
+ | `kilogram` | `"kilogram"` | `"kg"` | `kg=1` |
48
+ | `second` | `"second"` | `"s"` | `s=1` |
49
+ | `ampere` | `"ampere"` | `"A"` | `A=1` |
50
+ | `kelvin` | `"kelvin"` | `"K"` | `K=1` |
51
+ | `mole` | `"mole"` | `"mol"` | `mol=1` |
52
+ | `candle` | `"candle"` | `"cd"` | `candle=1` |
53
+
54
+ This is a spelling and symbol lookup. The conceptual role of the fundamental dimensions remains in the main skill.
55
+
56
+ ## Derived-unit lookup
57
+
58
+ The official page constructs these derived named units with `Unit.create(get_or_create_dimension(...), name, symbol)`:
59
+
60
+ | Name | Symbol | Dimension exponents shown by the source |
61
+ |---|---|---|
62
+ | `newton` | `N` | `m=1, kg=1, s=-2` |
63
+ | `pascal` | `Pa` | `m=-1, kg=1, s=-2` |
64
+ | `joule` | `J` | `m=2, kg=1, s=-2` |
65
+ | `watt` | `W` | `m=2, kg=1, s=-3` |
66
+ | `coulomb` | `C` | `s=1, A=1` |
67
+ | `volt` | `V` | `m=2, kg=1, s=-3, A=-1` |
68
+ | `farad` | `F` | `m=-2, kg=-1, s=4, A=2` |
69
+ | `ohm` | `ohm` | `m=2, kg=1, s=-3, A=-2` |
70
+ | `siemens` | `S` | `m=-2, kg=-1, s=3, A=2` |
71
+ | `weber` | `Wb` | `m=2, kg=1, s=-2, A=-1` |
72
+ | `tesla` | `T` | `kg=1, s=-2, A=-1` |
73
+ | `henry` | `H` | `m=2, kg=1, s=-2, A=-2` |
74
+ | `lux` | `lx` | `m=-2, cd=1` |
75
+ | `gray` | `Gy` | `m=2, s=-2` |
76
+ | `sievert` | `Sv` | `m=2, s=-2` |
77
+ | `katal` | `kat` | `s=-1, mol=1` |
78
+
79
+ ## Creating scaled units
80
+
81
+ The page constructs every supported prefix variant of a local `metre` object with `Unit.create_scaled_unit()`:
82
+
83
+ ```python
84
+ from brainunit import Unit, get_or_create_dimension
85
+
86
+ metre = Unit.create(get_or_create_dimension(m=1), "meter", "m")
87
+ # Unit("m")
88
+
89
+ kilometre = Unit.create_scaled_unit(metre, "k")
90
+ # Unit("km")
91
+ millimetre = Unit.create_scaled_unit(metre, "m")
92
+ # Unit("mm")
93
+ micrometre = Unit.create_scaled_unit(metre, "u")
94
+ # Unit("um")
95
+ ```
96
+
97
+ Inspect the resulting `Unit.scale` when validating a custom prefix:
98
+
99
+ ```python
100
+ assert kilometre.scale == 3
101
+ assert millimetre.scale == -3
102
+ assert micrometre.scale == -6
103
+ # Expected: all assertions pass.
104
+ ```
105
+
106
+ ## Source-backed gotchas
107
+
108
+ - Prefix symbols are case-sensitive: `M` is mega while `m` is milli.
109
+ - `da` is the two-character deka/deca prefix.
110
+ - `u` is the supported ASCII spelling for micro.
111
+ - The page says BrainUnit provides almost all units with prefixes. Do not infer that every conceivable unit-prefix combination is predefined without checking the package namespace.
112
+ - The source uses `metre` as a local variable but assigns the full unit name `"meter"`; distinguish Python variable spelling from `Unit.name`.
113
+
114
+ ## Sources mirrored
115
+
116
+ - https://brainx.chaobrain.com/brainunit/physical_units/standard_units.html
@@ -0,0 +1,104 @@
1
+ # Quantity inspection and conversion
2
+
3
+ Use this reference after the basic `Quantity` workflow is known. Open it when diagnosing scale or dimension issues, choosing an extraction boundary, formatting a value, or converting across compatible SI and non-SI units.
4
+
5
+ ## Contents
6
+
7
+ - [Inspection map](#inspection-map)
8
+ - [Conversion and extraction choices](#conversion-and-extraction-choices)
9
+ - [Compatibility probes](#compatibility-probes)
10
+ - [Boundary patterns](#boundary-patterns)
11
+ - [Source-backed gotchas](#source-backed-gotchas)
12
+
13
+ ## Inspection map
14
+
15
+ | API | Official meaning | Use when |
16
+ |---|---|---|
17
+ | `q.mantissa` | Raw numerical data without the unit | Inspecting the value in its current unit scale |
18
+ | `q.magnitude` | Alias for `q.mantissa` | Interoperating with code that uses magnitude terminology |
19
+ | `q.unit` | Attached `Unit`, including physical dimension and scale | Scale-sensitive inspection |
20
+ | `q.dim` | Physical dimension, independent of scale | Comparing metres with kilometres or volts with millivolts |
21
+ | `q.has_same_unit(other)` | Checks identical physical dimensions | Preflighting a conversion to another `Quantity` or `Unit` |
22
+ | `q.is_unitless` | True when the quantity has no physical unit | Guarding scalar-only boundaries |
23
+ | `u.split_mantissa_unit(q)` | Returns `(mantissa, unit)` | Decomposing and later reconstructing a quantity |
24
+
25
+ Despite its name, `Quantity.has_same_unit(other)` is documented as a dimension check: values in `mV` and `V` pass because their physical dimensions match.
26
+
27
+ ## Conversion and extraction choices
28
+
29
+ | Signature | Return | Behavior |
30
+ |---|---|---|
31
+ | `q.to(new_unit)` | `Quantity` | Rescales the mantissa and attaches a compatible target unit |
32
+ | `q.in_unit(unit, err_msg=None)` | `Quantity` | Behaves identically to `to()`; retained for API compatibility |
33
+ | `q.to_decimal(unit=Unit('1'))` | Plain number or array | Expresses the value in `unit` and removes the `Quantity` wrapper |
34
+ | `q.factorless()` | `Quantity` | Folds the unit factor into the mantissa and returns an equivalent factor-1 quantity |
35
+ | `q.item(*args)` | Scalar `Quantity` | Extracts one element without discarding its unit |
36
+ | `q.tolist()` | Nested list of scalar `Quantity` objects | Converts array structure while preserving units at every leaf |
37
+ | `q.repr_in_unit(precision=None)` | `str` | Formats the value in its current unit |
38
+ | `u.display_in_unit(q, unit)` | Display string | Displays a quantity in a selected compatible unit |
39
+
40
+ Use `to_decimal()` only at a boundary that requires bare numerical data. Use `item()` or `tolist()` when scalar or Python-container structure is needed but physical units must remain attached.
41
+
42
+ ```python
43
+ import brainunit as u
44
+ import jax.numpy as jnp
45
+
46
+ q = jnp.array([1.0, 2.0, 3.0]) * u.mV
47
+
48
+ q_volts = q.to(u.volt)
49
+ # Quantity([0.001 0.002 0.003], "V")
50
+ raw_volts = q.to_decimal(u.volt)
51
+ # Array([0.001, 0.002, 0.003], dtype=float32)
52
+ first = q.item(0)
53
+ # Expected: scalar Quantity 1 mV.
54
+ parts = q.tolist()
55
+ # Expected: [1 mV, 2 mV, 3 mV] as scalar Quantity leaves.
56
+ mantissa, unit = u.split_mantissa_unit(q)
57
+ # Expected: mantissa [1, 2, 3] and unit mV.
58
+ rebuilt = mantissa * unit
59
+ # Expected: equivalent to q, [1, 2, 3] mV.
60
+ ```
61
+
62
+ ## Compatibility probes
63
+
64
+ The conversion tutorial uses these package-level checks:
65
+
66
+ ```python
67
+ import brainunit as u
68
+
69
+ u.have_same_dim(u.meter, u.kmeter) # True
70
+ u.have_same_dim(u.meter, u.second) # False
71
+ u.have_same_dim(u.mV, u.volt) # True
72
+ u.have_same_dim(
73
+ u.newton,
74
+ u.kilogram * u.meter / u.second**2,
75
+ ) # True
76
+ u.is_dimensionless((5.0 * u.meter) / (2.0 * u.meter)) # True
77
+ ```
78
+
79
+ An incompatible target raises an error rather than silently reinterpreting the mantissa.
80
+
81
+ ## Boundary patterns
82
+
83
+ Convert to the unit expected by an external system before removing the wrapper:
84
+
85
+ ```python
86
+ voltage = jnp.array([100.0, 200.0, 300.0]) * u.mV
87
+ payload_in_volts = voltage.to_decimal(u.volt)
88
+ # Array([0.1, 0.2, 0.3], dtype=float32)
89
+ ```
90
+
91
+ Conversions are not limited to SI prefixes. The official tutorial demonstrates `mile` to `meter`, `kmeter`, and `foot`; `atmosphere` to `pascal`, `bar`, and `mmHg`; and `joule` to `calorie`, `electron_volt`, and `erg`.
92
+
93
+ ## Source-backed gotchas
94
+
95
+ - Dividing quantities with the same dimension produces a dimensionless result; depending on the input, the result is a plain numeric scalar or array rather than a unit-bearing `Quantity`.
96
+ - `float()` and `int()` accept dimensionless values. Direct `float()` on a unit-bearing `Quantity` raises `TypeError`; convert with `to_decimal(target_unit)` first.
97
+ - `q.mantissa` is expressed in the current unit scale. It is not automatically converted to a preferred external unit.
98
+ - `q.to_decimal()` validates that its argument is a `Unit` and raises on a dimension mismatch.
99
+ - `q.in_unit()` accepts `err_msg` for a custom dimension-mismatch message; `q.to()` does not expose that parameter.
100
+
101
+ ## Sources mirrored
102
+
103
+ - https://brainunit.readthedocs.io/physical_units/conversion.html
104
+ - https://brainunit.readthedocs.io/apis/generated/brainunit.Quantity.html
@@ -0,0 +1,203 @@
1
+ # Typing and runtime validation
2
+
3
+ Use this reference when a BrainUnit interface needs precise annotations, reusable physical-type aliases, runtime `isinstance` checks, or annotation-driven unit validation. The canonical `QuantityLike`, `UnitLike`, `Quantity[...]`, and `validate_units` workflow remains in the parent skill.
4
+
5
+ ## Annotation selection
6
+
7
+ | Form | Expresses | Use when |
8
+ |---|---|---|
9
+ | `QuantityLike` | A plain number, NumPy/JAX array, or existing `Quantity` | An adapter accepts values that will be normalized later |
10
+ | `UnitLike` | A `Unit`, unit string, or `None` | A parameter selects an optional target unit |
11
+ | `DimensionLike` | A `Dimension` or physical-type string | A parameter accepts either representation of a dimension |
12
+ | `u.Quantity[u.meter]` | A `Quantity` compatible with the meter dimension | A concrete unit makes the expected dimension clearest |
13
+ | `u.Quantity["length"]` | A `Quantity` with the named physical dimension | Scale is intentionally unspecified |
14
+ | `HAS_UNIT` | Any `Quantity`, regardless of dimension | Only the presence of a unit-aware value matters |
15
+ | `LENGTH`, `TIME`, `SPEED`, and other pre-built aliases | A reusable named physical dimension | Repeated signatures should share a short domain term |
16
+
17
+ `QuantityLike` is intentionally broad and does not require a unit. Normalize it with `u.math.asarray()` before relying on array or unit properties.
18
+
19
+ ```python
20
+ import brainunit as u
21
+ from brainunit.typing import QuantityLike, UnitLike
22
+
23
+
24
+ def normalize(values: QuantityLike, unit: UnitLike = None):
25
+ return u.math.asarray(values, unit=unit)
26
+ ```
27
+
28
+ ## Array and structural aliases
29
+
30
+ `brainunit.typing` re-exports these aliases for signatures shared with JAX and NumPy code.
31
+
32
+ | Alias | Meaning |
33
+ |---|---|
34
+ | `Array` | `jax.Array` when JAX is installed; a non-instantiable sentinel type on the no-JAX path |
35
+ | `ArrayLike` | `jax.Array`, `numpy.ndarray`, `numpy.number`, or `numpy.bool_`; excludes bare Python scalars |
36
+ | `ScalarOrArrayLike` | `ArrayLike` plus Python `bool`, `int`, `float`, and `complex` |
37
+ | `DTypeLike` | A NumPy/JAX-compatible dtype specifier |
38
+ | `Shape` | `Sequence[int]` |
39
+ | `Axis` | One integer axis |
40
+ | `Axes` | One integer axis or a sequence of integer axes |
41
+ | `PyTree` | An opaque arbitrarily nested PyTree alias |
42
+
43
+ Prefer `ArrayLike` when code reads `.shape`, `.ndim`, or `.dtype`; use `ScalarOrArrayLike` only when bare Python scalars are also valid.
44
+
45
+ The unit-specific core aliases are:
46
+
47
+ - `QuantityLike = int | float | complex | numpy.number | numpy.ndarray | jax.Array | Quantity`
48
+ - `UnitLike = Unit | str | None`; `None` means unitless or no requested target unit.
49
+ - `DimensionLike = Dimension | str`; strings use a known physical-type name.
50
+
51
+ ## Unit and physical-type annotations
52
+
53
+ `Quantity[item]` accepts a `Unit` or a physical-type string. Both forms create a type usable in annotations and runtime checks.
54
+
55
+ ```python
56
+ def kinetic_energy(
57
+ mass: u.Quantity[u.kilogram],
58
+ speed: u.Quantity[u.meter / u.second],
59
+ ) -> u.Quantity[u.joule]:
60
+ return 0.5 * mass * speed**2
61
+
62
+
63
+ def travel_time(
64
+ distance: u.Quantity["length"],
65
+ speed: u.Quantity["speed"],
66
+ ) -> u.Quantity["time"]:
67
+ return distance / speed
68
+ ```
69
+
70
+ For a unit item, the runtime type checks physical dimension rather than exact scale. For example, `u.Quantity[u.meter]` accepts a kilometer quantity unless `@validate_units(strict=True)` requests an exact unit match. A physical-type string carries no scale, so strict validation cannot make it scale-specific.
71
+
72
+ Unknown physical-type strings raise `ValueError`; non-`Unit`, non-string items inside `Quantity[...]` raise `TypeError`.
73
+
74
+ ## Physical-type names
75
+
76
+ The seven base dimensions and their accepted names are:
77
+
78
+ | Dimension | Accepted names |
79
+ |---|---|
80
+ | Length | `length` |
81
+ | Mass | `mass` |
82
+ | Time | `time` |
83
+ | Electric current | `current`, `electric current` |
84
+ | Temperature | `temperature` |
85
+ | Amount of substance | `substance`, `amount of substance` |
86
+ | Luminous intensity | `luminosity`, `luminous intensity` |
87
+ | Dimensionless | `dimensionless` |
88
+
89
+ Derived and compound physical-type strings are:
90
+
91
+ - `frequency`, `force`, `energy`, `power`, `pressure`, and `charge`
92
+ - `voltage` or `electric potential`
93
+ - `resistance`, `capacitance`, `conductance`, `magnetic flux`, `magnetic field`, and `inductance`
94
+ - `speed` or `velocity`, `acceleration`, `area`, `volume`, and `density`
95
+ - `momentum`, `angular velocity`, and `torque`
96
+
97
+ Names are normalized with surrounding whitespace removed and case lowered before lookup.
98
+
99
+ ## Pre-built physical-type aliases
100
+
101
+ Use pre-built aliases when the physical type is common and a short annotation improves a repeated signature.
102
+
103
+ | Group | Aliases |
104
+ |---|---|
105
+ | General | `HAS_UNIT`, `DIMENSIONLESS_TYPE` |
106
+ | Base dimensions | `LENGTH`, `MASS`, `TIME`, `CURRENT`, `TEMPERATURE`, `SUBSTANCE`, `LUMINOSITY` |
107
+ | Mechanics and thermodynamics | `FREQUENCY`, `FORCE`, `ENERGY`, `POWER`, `PRESSURE`, `SPEED`, `ACCELERATION`, `AREA`, `VOLUME`, `DENSITY` |
108
+ | Electromagnetism | `CHARGE`, `VOLTAGE`, `RESISTANCE`, `CAPACITANCE`, `CONDUCTANCE`, `MAGNETIC_FLUX`, `MAGNETIC_FIELD`, `INDUCTANCE` |
109
+
110
+ ```python
111
+ from brainunit.typing import LENGTH, SPEED, TIME
112
+
113
+
114
+ def displacement(speed: SPEED, duration: TIME) -> LENGTH:
115
+ return speed * duration
116
+ ```
117
+
118
+ The accepted string catalog is larger than the pre-built alias catalog. Use `Quantity["momentum"]`, `Quantity["angular velocity"]`, or `Quantity["torque"]` when no named alias is exported.
119
+
120
+ ## Runtime type helpers
121
+
122
+ `PhysicalType(name)` returns a runtime-checkable type whose `isinstance` behavior compares a quantity's dimension. `is_physical_type(obj)` reports whether an object is a type created by `PhysicalType`.
123
+
124
+ `quantity_type(item)` returns the same kind of runtime-checkable quantity type for a `Unit` or physical-type string. Prefer it in `isinstance` when a static analyzer flags parameterized checks such as `isinstance(x, u.Quantity["length"])`.
125
+
126
+ ```python
127
+ from brainunit.typing import PhysicalType, is_physical_type, quantity_type
128
+
129
+ distance = 2.0 * u.kmeter
130
+ length_type = quantity_type("length")
131
+ meter_type = quantity_type(u.meter)
132
+ speed_type = PhysicalType("speed")
133
+
134
+ assert isinstance(distance, length_type)
135
+ assert isinstance(distance, meter_type)
136
+ assert not isinstance(distance, speed_type)
137
+ assert is_physical_type(speed_type)
138
+ # Expected: all four assertions pass.
139
+ ```
140
+
141
+ All three positive checks are dimension-based. `quantity_type(u.meter)` does not require the stored scale to be exactly meters.
142
+
143
+ ## Annotation-driven runtime validation
144
+
145
+ `validate_units` inspects `Quantity[...]` argument annotations and validates each constrained argument on every call. It also recognizes legacy `typing.Annotated[Quantity, unit_or_physical_type]` metadata.
146
+
147
+ ```python
148
+ from brainunit.typing import validate_units
149
+
150
+
151
+ @validate_units
152
+ def rescale_length(value: u.Quantity[u.meter]):
153
+ return value.in_unit(u.meter)
154
+
155
+
156
+ compatible = rescale_length(2.0 * u.kmeter)
157
+ # Expected: 2000 m; compatible dimensions are accepted by default.
158
+
159
+
160
+ @validate_units(strict=True)
161
+ def require_meters(value: u.Quantity[u.meter]):
162
+ return value
163
+
164
+
165
+ exact = require_meters(2.0 * u.meter)
166
+ # Expected: 2 m; strict validation accepts the exact meter unit.
167
+ ```
168
+
169
+ Validation behavior:
170
+
171
+ - With `strict=False`, the default, a unit annotation requires compatible dimensions and permits a different scale.
172
+ - With `strict=True`, a unit annotation requires matching dimension and exact unit magnitude/scale.
173
+ - A physical-type annotation validates dimension only under either strictness setting because it specifies no scale.
174
+ - A constrained argument must be a `Quantity`; a bare number or array raises `TypeError`.
175
+ - A dimension mismatch raises `DimensionMismatchError`; a strict exact-unit mismatch raises `UnitMismatchError` in the current implementation.
176
+ - `None` arguments are skipped.
177
+ - Only arguments are validated. A return annotation documents the result but is not checked by the decorator.
178
+ - If a function has no recognized unit constraints, decoration leaves the function unchanged.
179
+
180
+ Use `@validate_units` when annotations should own the runtime contract. Use `@u.check_units(...)` when the existing keyword-driven declaration is clearer. Do not stack them by default.
181
+
182
+ ## Common gotchas
183
+
184
+ - Do not use `QuantityLike` to claim an argument is unit-bearing; the alias includes plain numbers and arrays.
185
+ - Do not assume `u.Quantity[u.meter]` means exact meters during `isinstance` or default validation; it means the meter dimension.
186
+ - Do not expect annotations alone to reject an invalid call; apply `validate_units` or another explicit runtime boundary.
187
+ - Do not rely on a return annotation for runtime validation; validate the returned quantity separately when that boundary is critical.
188
+ - The current BrainUnit compatibility package re-exports `saiunit.typing`, so generated documentation may display the underlying `saiunit` module or exception names. BrainUnit-facing code in this bundle uses the public `brainunit` namespace.
189
+ - Some released BrainUnit wheels may lag the official site and lack `brainunit.typing`. Upgrade BrainUnit together with its exact SaiUnit dependency; do not mix a legacy `brainunit.Quantity` with `saiunit.typing` objects from another release.
190
+
191
+ ## Sources mirrored
192
+
193
+ - https://brainx.chaobrain.com/brainunit/apis/brainunit.typing.html
194
+ - https://brainx.chaobrain.com/brainunit/apis/generated/brainunit.typing.PhysicalType.html
195
+ - https://brainx.chaobrain.com/brainunit/apis/generated/brainunit.typing.is_physical_type.html
196
+ - https://brainx.chaobrain.com/brainunit/apis/generated/brainunit.typing.quantity_type.html
197
+ - https://brainx.chaobrain.com/brainunit/apis/generated/brainunit.typing.QuantityLike.html
198
+ - https://brainx.chaobrain.com/brainunit/apis/generated/brainunit.typing.UnitLike.html
199
+ - https://brainx.chaobrain.com/brainunit/apis/generated/brainunit.typing.DimensionLike.html
200
+ - https://brainx.chaobrain.com/brainunit/apis/generated/brainunit.typing.validate_units.html
201
+ - https://brainx.chaobrain.com/brainunit/_modules/saiunit/typing.html
202
+ - https://github.com/chaobrain/saiunit/blob/main/brainunit/brainunit/typing.py
203
+ - https://github.com/chaobrain/saiunit/blob/main/saiunit/_typing.py
@@ -0,0 +1,140 @@
1
+ # Unit structure and definition
2
+
3
+ Use this reference to inspect scale encoding, distinguish dimension from magnitude, compare units, combine existing units, or define a named, factored, or prefixed custom unit.
4
+
5
+ ## Contents
6
+
7
+ - [Unit anatomy](#unit-anatomy)
8
+ - [Comparison methods](#comparison-methods)
9
+ - [Combining units](#combining-units)
10
+ - [Defining units](#defining-units)
11
+ - [Source-backed gotchas](#source-backed-gotchas)
12
+
13
+ ## Unit anatomy
14
+
15
+ The official API represents a unit with dimension, scale, base, factor, and naming metadata:
16
+
17
+ ```text
18
+ Unit(dim=None, scale=0, base=10.0, factor=1.0,
19
+ name=None, dispname=None, is_fullname=True, display_parts=None)
20
+ ```
21
+
22
+ | Property | Official meaning |
23
+ |---|---|
24
+ | `unit.dim` | Physical dimensions |
25
+ | `unit.scale` | Exponent applied to `base`; `mvolt.scale == -3` |
26
+ | `unit.base` | Base of the scale exponent; SI prefixes use `10` |
27
+ | `unit.factor` | Additional conversion factor, such as `4.184` for calorie relative to joule |
28
+ | `unit.magnitude` | `factor * base ** scale` |
29
+ | `unit.name` | Full name such as `'volt'` or `'mvolt'` |
30
+ | `unit.dispname` | Display symbol such as `'V'` or `'mV'` |
31
+ | `unit.is_unitless` | Dimensionless with scale `0` and factor `1.0` |
32
+ | `unit.should_display_unit` | True for physical units and named dimensionless units such as radians |
33
+
34
+ `unit.factorless()` returns an equivalent unit with factor `1`; when a registered unit with the same dimension and scale exists, that standard unit may be returned. `unit.reverse()` returns the reciprocal unit.
35
+
36
+ ## Comparison methods
37
+
38
+ | Exact signature | Comparison |
39
+ |---|---|
40
+ | `has_same_dim(other)` | Same physical dimensions |
41
+ | `has_same_base(other)` | Same scale base |
42
+ | `has_same_magnitude(other)` | Same `scale`, `base`, and `factor` components |
43
+
44
+ `has_same_magnitude()` is component-wise. A unit represented with `scale=3` and one represented with `factor=1000` can have the same computed magnitude but compare unequal.
45
+
46
+ ```python
47
+ import brainunit as u
48
+
49
+ u.volt.has_same_dim(u.mvolt) # True
50
+ u.volt.has_same_dim(u.amp) # False
51
+ u.mvolt.has_same_magnitude(u.mamp) # True
52
+ u.mvolt.has_same_magnitude(u.volt) # False
53
+ ```
54
+
55
+ ## Combining units
56
+
57
+ Units and quantities use normal Python numeric operators. The official tutorial constructs volt from component units and compares it to the predefined unit:
58
+
59
+ ```python
60
+ import brainunit as u
61
+
62
+ volt = u.meter2 * u.kilogram / (u.second3 * u.ampere)
63
+ assert volt == u.volt
64
+ # Expected: assertion passes; the derived unit is Unit("V").
65
+ ```
66
+
67
+ Use `unit.reverse()` when reciprocal intent should be explicit:
68
+
69
+ ```python
70
+ frequency = u.second.reverse()
71
+ # Unit("Hz")
72
+ inverse_length = u.metre.reverse()
73
+ # Unit("1 / m")
74
+ ```
75
+
76
+ ## Defining units
77
+
78
+ Exact constructors:
79
+
80
+ ```text
81
+ Unit.create(dim, name, dispname, scale=0, base=10.0, factor=1.0)
82
+ Unit.create_scaled_unit(baseunit, scalefactor)
83
+ ```
84
+
85
+ Define a named unit from an existing dimension when a non-prefix conversion factor is needed:
86
+
87
+ ```python
88
+ import brainunit as u
89
+
90
+ calorie = u.Unit.create(
91
+ u.joule.dim,
92
+ 'calorie',
93
+ 'cal',
94
+ factor=4.184,
95
+ )
96
+ # Unit("cal")
97
+ ```
98
+
99
+ Define a fundamental or compound unit through `get_or_create_dimension()`:
100
+
101
+ ```python
102
+ metre = u.Unit.create(
103
+ u.get_or_create_dimension(m=1),
104
+ 'metre',
105
+ 'm',
106
+ base=10.0,
107
+ )
108
+ # Unit("m")
109
+
110
+ volt = u.Unit.create(
111
+ u.get_or_create_dimension(m=2, kg=1, s=-3, A=-1),
112
+ 'volt',
113
+ 'V',
114
+ )
115
+ # Unit("V")
116
+ ```
117
+
118
+ Create a supported prefixed scale from a base unit:
119
+
120
+ ```python
121
+ kilometre = u.Unit.create_scaled_unit(metre, 'k')
122
+ # Unit("km")
123
+ ratio = 1 * kilometre / (1 * metre)
124
+ # Expected: 1000.0, a plain dimensionless value.
125
+ ```
126
+
127
+ See `prefix-library.md` for the complete prefix symbol and exponent table.
128
+
129
+ ## Source-backed gotchas
130
+
131
+ - `Unit.create()` supports only base `10`; other values raise `ValueError`.
132
+ - Use `factor` for conversions such as calorie-to-joule; use `scale` for powers of `base`.
133
+ - `is_unitless` requires dimensionless dimension, zero scale, and factor `1.0`; a scaled dimensionless unit is not unitless by this definition.
134
+ - `factorless()` intentionally avoids blindly replacing every alias, because that could rename units such as becquerel to hertz or steradian to radian.
135
+ - `create_scaled_unit(baseunit, scalefactor)` takes a prefix string such as `'u'` or `'k'`, not a numeric multiplier.
136
+
137
+ ## Sources mirrored
138
+
139
+ - https://brainunit.readthedocs.io/apis/generated/brainunit.Unit.html
140
+ - https://brainunit.readthedocs.io/advanced_tutorials/combining_and_defining.html