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.
- package/LICENSE +1 -1
- package/README.md +29 -64
- package/adapters/gemini.js +7 -0
- package/adapters/opencode.js +7 -0
- package/adapters/windsurf.js +7 -0
- package/{lib → installation/lib}/installer.js +8 -5
- package/manifest.json +7 -1
- package/package.json +25 -10
- package/skills/braincell/SKILL.md +182 -0
- package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
- package/skills/braincell/references/channel-library.md +170 -0
- package/skills/braincell/references/ion-library.md +154 -0
- package/skills/braincell/references/mixions-for-adaptation.md +81 -0
- package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
- package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
- package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
- package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
- package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
- package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
- package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
- package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
- package/skills/braincell/references/scripts/channel_ablation.py +61 -0
- package/skills/braincell/references/scripts/fi_curve.py +68 -0
- package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
- package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
- package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
- package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
- package/skills/braincell/references/solver-library-with-effects.md +188 -0
- package/skills/brainevent/SKILL.md +268 -0
- package/skills/brainevent/references/connectivity-variants.md +312 -0
- package/skills/brainevent/references/custom-operators-cpu.md +304 -0
- package/skills/brainevent/references/custom-operators-gpu.md +468 -0
- package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
- package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
- package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
- package/skills/brainevent/references/sparse-formats.md +182 -0
- package/skills/brainevent/references/synaptic-plasticity.md +285 -0
- package/skills/brainpy-state/SKILL.md +232 -0
- package/skills/brainpy-state/references/array-creation.md +158 -0
- package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
- package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
- package/skills/brainpy-state/references/braintools/metric.md +152 -0
- package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
- package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
- package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
- package/skills/brainpy-state/references/component-selection.md +273 -0
- package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
- package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
- package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
- package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
- package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
- package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
- package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
- package/skills/brainpy-state/references/projection-patterns.md +125 -0
- package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
- package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
- package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
- package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
- package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
- package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
- package/skills/brainstate/SKILL.md +399 -0
- package/skills/brainstate/agents/openai.yaml +4 -0
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
- package/skills/brainstate/references/collective_model_operations.md +195 -0
- package/skills/brainstate/references/extension_mechanisms.md +293 -0
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
- package/skills/brainstate/references/model-interop-and-migration.md +305 -0
- package/skills/brainstate/references/simulation-environment.md +117 -0
- package/skills/brainstate/references/size-inference-variations.md +279 -0
- package/skills/brainstate/references/state-graph-operations.md +216 -0
- package/skills/brainstate/references/state_collections_and_utilities.md +235 -0
- package/skills/brainstate/scripts/integrator_rnn.py +359 -0
- package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
- package/skills/brainstate/scripts/modern_cnn.py +73 -0
- package/skills/brainstate/scripts/resnet.py +130 -0
- package/skills/brainunit/SKILL.md +287 -0
- package/skills/brainunit/references/array-creation.md +158 -0
- package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
- package/skills/brainunit/references/array-mechanics.md +165 -0
- package/skills/brainunit/references/math-function-library.md +433 -0
- package/skills/brainunit/references/physical-constant-library.md +58 -0
- package/skills/brainunit/references/prefix-library.md +116 -0
- package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
- package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
- package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
- package/skills/brainx-general-guard/SKILL.md +153 -0
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
- package/skills/brainx-install/SKILL.md +2 -2
- package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
- /package/{bin → installation/bin}/brainx.js +0 -0
- /package/{lib → installation/lib}/adapter-transaction.js +0 -0
- /package/{lib → installation/lib}/bundle.js +0 -0
- /package/{lib → installation/lib}/cli.js +0 -0
- /package/{lib → installation/lib}/constants.js +0 -0
- /package/{lib → installation/lib}/hash.js +0 -0
- /package/{lib → installation/lib}/paths.js +0 -0
- /package/{lib → installation/lib}/prompts.js +0 -0
- /package/{lib → installation/lib}/receipt.js +0 -0
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""ModernCNN composition and fit-mode forward-pass reference.
|
|
2
|
+
|
|
3
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/core/04_activations_and_normalization.html
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import brainstate
|
|
7
|
+
import brainunit as u
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ModernCNN(brainstate.nn.Module):
|
|
11
|
+
"""CNN with modern activations and normalization."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, num_classes=10):
|
|
14
|
+
super().__init__()
|
|
15
|
+
|
|
16
|
+
# Block 1: Conv + BatchNorm + GELU
|
|
17
|
+
self.conv1 = brainstate.nn.Conv2d((32, 32, 3), out_channels=64, kernel_size=(3, 3), padding='SAME')
|
|
18
|
+
self.bn1 = brainstate.nn.BatchNorm2d((32, 32, 64))
|
|
19
|
+
self.act1 = brainstate.nn.GELU()
|
|
20
|
+
self.pool1 = brainstate.nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
|
|
21
|
+
|
|
22
|
+
# Block 2
|
|
23
|
+
self.conv2 = brainstate.nn.Conv2d((16, 16, 64), out_channels=128, kernel_size=(3, 3), padding='SAME')
|
|
24
|
+
self.bn2 = brainstate.nn.BatchNorm2d((16, 16, 128))
|
|
25
|
+
self.act2 = brainstate.nn.GELU()
|
|
26
|
+
self.pool2 = brainstate.nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2), in_size=self.bn2.out_size)
|
|
27
|
+
|
|
28
|
+
# Classifier
|
|
29
|
+
self.fc1 = brainstate.nn.Linear((128 * 8 * 8,), (256,))
|
|
30
|
+
self.ln = brainstate.nn.LayerNorm((256,))
|
|
31
|
+
self.act3 = brainstate.nn.GELU()
|
|
32
|
+
self.dropout = brainstate.nn.Dropout(prob=0.5)
|
|
33
|
+
self.fc2 = brainstate.nn.Linear((256,), (num_classes,))
|
|
34
|
+
|
|
35
|
+
def update(self, x):
|
|
36
|
+
# Block 1
|
|
37
|
+
x = self.conv1(x)
|
|
38
|
+
x = self.bn1(x)
|
|
39
|
+
x = self.act1(x)
|
|
40
|
+
x = self.pool1(x)
|
|
41
|
+
|
|
42
|
+
# Block 2
|
|
43
|
+
x = self.conv2(x)
|
|
44
|
+
x = self.bn2(x)
|
|
45
|
+
x = self.act2(x)
|
|
46
|
+
x = self.pool2(x)
|
|
47
|
+
|
|
48
|
+
# Classifier
|
|
49
|
+
x = u.math.flatten(x, start_axis=1)
|
|
50
|
+
x = self.fc1(x)
|
|
51
|
+
x = self.ln(x)
|
|
52
|
+
x = self.act3(x)
|
|
53
|
+
x = self.dropout(x)
|
|
54
|
+
x = self.fc2(x)
|
|
55
|
+
|
|
56
|
+
return x
|
|
57
|
+
|
|
58
|
+
# Create and test
|
|
59
|
+
brainstate.random.seed(0)
|
|
60
|
+
model = ModernCNN(num_classes=10)
|
|
61
|
+
|
|
62
|
+
# Forward pass
|
|
63
|
+
x = brainstate.random.randn(4, 32, 32, 3) # 4 images
|
|
64
|
+
with brainstate.environ.context(fit=True) as env:
|
|
65
|
+
logits = model(x)
|
|
66
|
+
|
|
67
|
+
print("Modern CNN with GELU + BatchNorm + LayerNorm:")
|
|
68
|
+
print(model)
|
|
69
|
+
print()
|
|
70
|
+
print("Input:", x.shape)
|
|
71
|
+
print("Output:", logits.shape)
|
|
72
|
+
print()
|
|
73
|
+
print("Logits:", logits[0])
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Residual connections and dynamic child registration for BrainState Modules.
|
|
2
|
+
|
|
3
|
+
Source: https://brainx.chaobrain.com/brainstate/tutorials/core/02_modules_and_graph.html
|
|
4
|
+
Role: Mirrors the tutorial's custom helpers and ``ResidualBlock``/``ResNet``
|
|
5
|
+
example as a standalone script.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import brainstate
|
|
9
|
+
import jax.numpy as jnp
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Linear(brainstate.nn.Module):
|
|
13
|
+
"""A linear transformation: y = W @ x + b"""
|
|
14
|
+
|
|
15
|
+
def __init__(self, in_features, out_features, use_bias=True):
|
|
16
|
+
super().__init__()
|
|
17
|
+
|
|
18
|
+
self.in_features = in_features
|
|
19
|
+
self.out_features = out_features
|
|
20
|
+
self.use_bias = use_bias
|
|
21
|
+
|
|
22
|
+
# Initialize weight with Xavier/Glorot initialization
|
|
23
|
+
std = jnp.sqrt(2.0 / (in_features + out_features))
|
|
24
|
+
self.weight = brainstate.ParamState(
|
|
25
|
+
brainstate.random.randn(in_features, out_features) * std
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
# Initialize bias to zero
|
|
29
|
+
if use_bias:
|
|
30
|
+
self.bias = brainstate.ParamState(jnp.zeros(out_features))
|
|
31
|
+
|
|
32
|
+
def update(self, x):
|
|
33
|
+
"""Forward pass.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
x: Input tensor of shape (..., in_features)
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
Output tensor of shape (..., out_features)
|
|
40
|
+
"""
|
|
41
|
+
out = x @ self.weight.value
|
|
42
|
+
if self.use_bias:
|
|
43
|
+
out = out + self.bias.value
|
|
44
|
+
return out
|
|
45
|
+
|
|
46
|
+
def __repr__(self):
|
|
47
|
+
return f"Linear(in_features={self.in_features}, out_features={self.out_features}, use_bias={self.use_bias})"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class LeakyReLU(brainstate.nn.Module):
|
|
51
|
+
"""Leaky ReLU activation: y = max(alpha * x, x)"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, negative_slope=0.01):
|
|
54
|
+
super().__init__()
|
|
55
|
+
self.negative_slope = negative_slope
|
|
56
|
+
|
|
57
|
+
def update(self, x):
|
|
58
|
+
return jnp.where(x > 0, x, self.negative_slope * x)
|
|
59
|
+
|
|
60
|
+
def __repr__(self):
|
|
61
|
+
return f"LeakyReLU(negative_slope={self.negative_slope})"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class ResidualBlock(brainstate.nn.Module):
|
|
65
|
+
"""Residual block: y = F(x) + x"""
|
|
66
|
+
|
|
67
|
+
def __init__(self, dim):
|
|
68
|
+
super().__init__()
|
|
69
|
+
|
|
70
|
+
# Two linear layers with activation in between
|
|
71
|
+
self.linear1 = Linear(dim, dim)
|
|
72
|
+
self.activation = LeakyReLU(0.0)
|
|
73
|
+
self.linear2 = Linear(dim, dim)
|
|
74
|
+
|
|
75
|
+
def update(self, x):
|
|
76
|
+
# Compute residual
|
|
77
|
+
residual = x
|
|
78
|
+
|
|
79
|
+
# Forward through layers
|
|
80
|
+
out = self.linear1(x)
|
|
81
|
+
out = self.activation(out)
|
|
82
|
+
out = self.linear2(out)
|
|
83
|
+
|
|
84
|
+
# Add residual
|
|
85
|
+
return out + residual
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ResNet(brainstate.nn.Module):
|
|
89
|
+
"""Simple ResNet with multiple residual blocks."""
|
|
90
|
+
|
|
91
|
+
def __init__(self, input_dim, hidden_dim, output_dim, n_blocks=3):
|
|
92
|
+
super().__init__()
|
|
93
|
+
|
|
94
|
+
# Input projection
|
|
95
|
+
self.input_proj = Linear(input_dim, hidden_dim)
|
|
96
|
+
|
|
97
|
+
# Residual blocks
|
|
98
|
+
self.blocks = []
|
|
99
|
+
for i in range(n_blocks):
|
|
100
|
+
block = ResidualBlock(hidden_dim)
|
|
101
|
+
setattr(self, f"block_{i}", block)
|
|
102
|
+
self.blocks.append(block)
|
|
103
|
+
|
|
104
|
+
# Output projection
|
|
105
|
+
self.output_proj = Linear(hidden_dim, output_dim)
|
|
106
|
+
|
|
107
|
+
def update(self, x):
|
|
108
|
+
# Project to hidden dimension
|
|
109
|
+
x = self.input_proj(x)
|
|
110
|
+
|
|
111
|
+
# Pass through residual blocks
|
|
112
|
+
for block in self.blocks:
|
|
113
|
+
x = block(x)
|
|
114
|
+
|
|
115
|
+
# Project to output
|
|
116
|
+
x = self.output_proj(x)
|
|
117
|
+
return x
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# Create ResNet
|
|
121
|
+
brainstate.random.seed(0)
|
|
122
|
+
resnet = ResNet(input_dim=10, hidden_dim=32, output_dim=5, n_blocks=3)
|
|
123
|
+
|
|
124
|
+
# Forward pass
|
|
125
|
+
x = brainstate.random.randn(10)
|
|
126
|
+
y = resnet(x)
|
|
127
|
+
|
|
128
|
+
print("ResNet:")
|
|
129
|
+
print(resnet)
|
|
130
|
+
print(f"\nOutput shape: {y.shape}")
|
|
@@ -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
|