brainx-skill 1.0.3 → 1.0.8

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 (117) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +29 -64
  3. package/adapters/gemini.js +7 -0
  4. package/adapters/opencode.js +7 -0
  5. package/adapters/windsurf.js +7 -0
  6. package/{lib → installation/lib}/installer.js +8 -5
  7. package/manifest.json +7 -1
  8. package/package.json +25 -10
  9. package/skills/braincell/SKILL.md +182 -0
  10. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  11. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
  12. package/skills/braincell/references/channel-library.md +170 -0
  13. package/skills/braincell/references/ion-library.md +154 -0
  14. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  15. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  16. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  17. package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
  18. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  19. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  20. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  21. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
  22. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  23. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  24. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  25. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  26. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  27. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  28. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  29. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  30. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  31. package/skills/brainevent/SKILL.md +268 -0
  32. package/skills/brainevent/references/connectivity-variants.md +312 -0
  33. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  34. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  35. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  36. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  37. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  38. package/skills/brainevent/references/sparse-formats.md +182 -0
  39. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  40. package/skills/brainpy-state/SKILL.md +232 -0
  41. package/skills/brainpy-state/references/array-creation.md +158 -0
  42. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  43. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  44. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  45. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  46. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  47. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  48. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  49. package/skills/brainpy-state/references/component-selection.md +273 -0
  50. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  51. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  52. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  53. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  54. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  55. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  56. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  57. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  58. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  59. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  60. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  61. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  62. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  63. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  64. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  65. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  66. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  67. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  68. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  69. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  70. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  71. package/skills/brainstate/SKILL.md +399 -0
  72. package/skills/brainstate/agents/openai.yaml +4 -0
  73. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
  75. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
  76. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  77. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
  78. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
  79. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
  80. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
  81. package/skills/brainstate/references/collective_model_operations.md +195 -0
  82. package/skills/brainstate/references/extension_mechanisms.md +293 -0
  83. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
  84. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
  85. package/skills/brainstate/references/model-interop-and-migration.md +305 -0
  86. package/skills/brainstate/references/simulation-environment.md +117 -0
  87. package/skills/brainstate/references/size-inference-variations.md +279 -0
  88. package/skills/brainstate/references/state-graph-operations.md +216 -0
  89. package/skills/brainstate/references/state_collections_and_utilities.md +235 -0
  90. package/skills/brainstate/scripts/integrator_rnn.py +359 -0
  91. package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
  92. package/skills/brainstate/scripts/modern_cnn.py +73 -0
  93. package/skills/brainstate/scripts/resnet.py +130 -0
  94. package/skills/brainunit/SKILL.md +287 -0
  95. package/skills/brainunit/references/array-creation.md +158 -0
  96. package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
  97. package/skills/brainunit/references/array-mechanics.md +165 -0
  98. package/skills/brainunit/references/math-function-library.md +433 -0
  99. package/skills/brainunit/references/physical-constant-library.md +58 -0
  100. package/skills/brainunit/references/prefix-library.md +116 -0
  101. package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
  102. package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
  103. package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
  104. package/skills/brainx-general-guard/SKILL.md +153 -0
  105. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
  106. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
  107. package/skills/brainx-install/SKILL.md +2 -2
  108. package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
  109. /package/{bin → installation/bin}/brainx.js +0 -0
  110. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  111. /package/{lib → installation/lib}/bundle.js +0 -0
  112. /package/{lib → installation/lib}/cli.js +0 -0
  113. /package/{lib → installation/lib}/constants.js +0 -0
  114. /package/{lib → installation/lib}/hash.js +0 -0
  115. /package/{lib → installation/lib}/paths.js +0 -0
  116. /package/{lib → installation/lib}/prompts.js +0 -0
  117. /package/{lib → installation/lib}/receipt.js +0 -0
@@ -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
@@ -0,0 +1,153 @@
1
+ ---
2
+ name: brainx-general-guard
3
+ description: Prevents cross-cutting BrainX misuse and infrastructure mistakes, including wrong package selection, bypassed units, raw JAX transforms on stateful code, and unnecessary custom NumPy/JAX simulations. Use when a request needs BrainX domain routing, safety guardrails, common mistake correction, or confirmation that BrainX APIs should be used.
4
+ ---
5
+
6
+ # brainx-general-guard/
7
+
8
+ ## Concepts
9
+
10
+ • BrainState mental model
11
+ Three nouns carry the whole framework: State, Module, and Transform.
12
+ **Source mirrored:** https://brainx.chaobrain.com/brainstate/getting_started/thinking_in_brainstate.html
13
+
14
+ • State-aware transforms
15
+ BrainState transformations mirror JAX’s, but understand State; reads and writes are threaded through compiled functions automatically.
16
+ **Source mirrored:** https://brainx.chaobrain.com/brainstate/getting_started/thinking_in_brainstate.html
17
+
18
+ • BrainUnit / BrainCell unit guard
19
+ In braincell, every physical quantity carries an explicit unit; passing a bare number where a quantity is expected raises TypeError.
20
+ **Source mirrored:** https://brainx.chaobrain.com/braincell/concepts/units.html
21
+
22
+ • BrainCell modeling guard
23
+ A mechanism is anything installed on a cell that affects dynamics; in braincell, mechanisms are declarative and describe what to install without touching JAX, time, or runtime state.
24
+ **Source mirrored:** https://brainx.chaobrain.com/braincell/concepts/mechanisms.html
25
+
26
+ https://brainx.chaobrain.com/brainstate/tutorials/core/08_randomness.html
27
+
28
+
29
+ ## Conditional reference routing
30
+
31
+ ```text
32
+ brainx-general-guard/
33
+ └── brainstate-randomness-reproducibility/
34
+ └── randomness-and-reproducibility.md
35
+ └── advanced-randomness.md
36
+ ```
37
+
38
+ Open `skills/brainx-install/SKILL.md` only for installation, setup, import errors, backend selection, CUDA/GPU/TPU, JAX device validation, version pinning, or package mismatch. Keep normal modeling tasks from loading install content.
39
+
40
+ Open `skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md` only when the task involves seed control, random trials, stochastic state, dropout/noise, random data, transformed randomness, or reproducibility.
41
+
42
+ Do not open `skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md` directly. The local randomness parent is its only inbound selection route.
43
+
44
+ Keep global BrainX guardrails active: do not invent APIs, prefer official examples, use BrainState transforms for BrainState state, use BrainUnit quantities for physical parameters, and prefer built-ins before custom implementation.
45
+
46
+ Domain routing guard
47
+
48
+ #### Explanation text
49
+
50
+ Route before coding: BrainState for State / Module / Transform, BrainCell for cells / mechanisms / channels / ions, BrainUnit for physical quantities and dimensional safety, BrainMass only when the official task is population / whole-brain mass modeling.
51
+
52
+ Use BrainState JIT for stateful modules
53
+
54
+ **Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
55
+
56
+ #### Script
57
+
58
+ ```python
59
+ import jax
60
+ import jax.numpy as jnp
61
+ import brainstate
62
+ class RunningMean(brainstate.nn.Module):
63
+ def __init__(self):
64
+ super().__init__()
65
+ self.sum = brainstate.HiddenState(jnp.array(0.0))
66
+ self.count = brainstate.HiddenState(jnp.array(0))
67
+ def __call__(self, batch: jax.Array) -> jax.Array:
68
+ self.sum.value += jnp.sum(batch)
69
+ self.count.value += batch.size
70
+ return self.sum.value / self.count.value
71
+ tracker = RunningMean()
72
+ @brainstate.transform.jit
73
+ def update_running_mean(batch: jax.Array) -> jax.Array:
74
+ return tracker(batch)
75
+ for step in range(3):
76
+ data = jnp.arange(4.0) + step
77
+ print(f'step {step}: mean={float(update_running_mean(data)):.2f}')
78
+ float(tracker.sum.value), int(tracker.count.value)
79
+ ```
80
+
81
+ #### Explanation text
82
+
83
+ brainstate.transform.jit understands State objects and automatically wires read/write traces into the compiled function; raw jax.jit requires explicitly splitting and merging module state.
84
+ **Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/01_jit_and_compilation.html
85
+
86
+ Use BrainState loop transforms for stateful loops
87
+
88
+ **Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html
89
+
90
+ #### Script
91
+
92
+ ```python
93
+ # Example 2: Stateful for_loop
94
+ class Accumulator(brainstate.nn.Module):
95
+ """Simple accumulator that tracks total and count."""
96
+ def __init__(self):
97
+ super().__init__()
98
+ self.total = brainstate.ShortTermState(jnp.array(0.0))
99
+ self.count = brainstate.ShortTermState(jnp.array(0))
100
+ def process(self, x):
101
+ self.total.value = self.total.value + x
102
+ self.count.value = self.count.value + 1
103
+ return self.total.value / self.count.value # running average
104
+ acc = Accumulator()
105
+ data = jnp.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
106
+ running_averages = for_loop(acc.process, data)
107
+ print("Data:", data)
108
+ print("Running averages:", running_averages)
109
+ print(f"\n Final state: total={acc.total.value}, count={acc.count.value}")
110
+ print(f"Final average: {acc.total.value / acc.count.value}")
111
+ ```
112
+
113
+ #### Explanation text
114
+
115
+ Control-flow APIs in brainstate.transform provide JAX-compatible loops and conditionals while safely handling State objects; loop transformations compile to a single JAX primitive, reducing compilation overhead.
116
+ **Source mirrored:** https://brainx.chaobrain.com/brainstate/tutorials/transformations/05_control_flow.html
117
+
118
+ Use units before biological simulation
119
+
120
+ **Source mirrored:** https://brainx.chaobrain.com/braincell/concepts/units.html
121
+
122
+ #### Script
123
+
124
+ ```python
125
+ import numpy as np
126
+ import jax.numpy as jnp
127
+ import brainunit as u
128
+ v_rest = -65.0 * u.mV # scalar
129
+ dt = 0.1 * u.ms
130
+ lengths = np.array([10.5, 20.0]) * u.um # numpy array
131
+ coords = jnp.zeros((10, 3)) * u.um # JAX array
132
+ radii = [2.0, 3.0, 4.0] * u.um # list
133
+ ```
134
+
135
+ #### Explanation text
136
+
137
+ Silent unit mismatches are one of the most common and hardest-to-find bugs in neural modeling; BrainCell requires units everywhere and catches dimensional errors immediately.
138
+ **Source mirrored:** https://brainx.chaobrain.com/braincell/concepts/units.html
139
+
140
+ ## Common mistakes -> Fix
141
+
142
+ • writing random NumPy simulation code -> route first to BrainState / BrainCell / BrainUnit.
143
+ • using raw jax.jit on stateful BrainState modules -> use brainstate.transform.jit; raw jax.jit requires manual state threading.
144
+ • Python for-loop around state updates when compiling/scanning -> use BrainState scan, for_loop, or control-flow transform.
145
+ • passing bare floats into BrainCell mechanisms -> attach brainunit units.
146
+ • treating BrainCell as generic ODE code -> use cells, ions, channels, mechanisms, and integrators.
147
+ • writing custom ion channel first -> check built-in braincell.channel list first.
148
+ • inventing APIs -> open the official example/source first; do not fabricate a standalone script when no official pattern exists.
149
+ • loading install guidance for ordinary modeling -> use `skills/brainx-install/SKILL.md` only after install/setup/backend/package evidence appears.
150
+
151
+ ## Script references
152
+
153
+ None. This guard has no standalone script reference; its compact guard examples remain inline.