Tensor API
Import tensor helpers from bilt. See Domains and tensors
for an introduction, Units API for physical units, and
Quantity annotations and typing for scalar/tensor system fields.
Construction and inspection
| API | Meaning |
|---|---|
dim(name) / Dim(name) |
Named array dimension. Dimensions compare by name; use different names for independent axes. |
domain(*dims) / Domain(dims=()) |
Ordered domain with no repeated dimensions. |
domain() / Domain.scalar() |
Empty domain for scalar values. |
as_domain(value) |
Convert a Dim or iterable of dimensions to a domain; return an existing domain unchanged. |
tensor(values, *, over=None, domain=None, unit=None) |
Construct a tensor from array-like data. Supply either over or domain for non-scalar data. |
Tensor(values, domain, unit=None) |
Direct constructor with an explicit domain. |
tensor(value) / Tensor.scalar(value, unit=None) |
Rank-zero tensor. |
t.values, t.shape, t.ndim |
NumPy array, shape and rank. |
t.domain, t.domain.dims, t.domain.is_scalar |
Domain, ordered dimensions and scalar-domain flag. |
t.unit |
Physical unit, or None. |
dimension.name |
Dimension name. |
from bilt import dim, domain, tensor
time = dim("time")
values = tensor([1.0, 3.0, 5.0], over=time)
assert values.domain == domain(time)
assert values.shape == (3,)
Array rank must match the number of dimensions. During evaluation, shared dimensions must have equal lengths. Missing dimensions broadcast; shared ones align by name. Result axes follow the evaluation's dimension binding order.
Units
| API | Meaning |
|---|---|
tensor(values, over=time, unit=meter) |
Label the numerical values with a unit. |
t.convert_to(unit) |
Rescale values to a compatible unit, retaining the domain. |
t * unit |
Label an unlabelled tensor or compose its unit; values are unchanged. |
unit * t, t / unit |
Compose units on an already labelled tensor. |
Use Annotated[QuantityTensor, LENGTH] for tensor-only unit-bearing fields or equation parameters. For pointwise quantities that can be scalars or tensors, use Annotated[Quantity | QuantityTensor, LENGTH]. Dimensioned Annotated[Tensor, LENGTH] declarations are no longer supported.
Bare Tensor ports are outside the physical unit system. With a non-optional
unit, tensor(..., unit=...) returns QuantityTensor; without one it returns
Tensor. Computed declared
quantities use coherent units; convert returned tensors for display.
Reductions
Use these methods in decorated relationships. Each takes one named dimension present in the operand's domain and removes it from the result's domain.
| Method | Result |
|---|---|
x.mean(dim) |
Arithmetic mean. |
x.sum(dim) |
Sum. |
x.min(dim) |
Minimum. |
x.max(dim) |
Maximum. |
x.prod(dim) |
Product. |
In unit-aware equations, mean/sum/min/max retain dimensionality and tags.
prod requires a dimensionless operand; sum refuses absolute readings.
Reducing the last dimension gives a scalar domain. Unit-aware Tensor-declared
outputs remain rank-zero tensors; other scalar-domain outputs are numerical
scalars or declared quantities.
Transforms: use a single return statement, applying reductions directly to named parameters with a dimension captured by a global or closure name:
from bilt import Tensor, transform
@transform
def averaged(values: Tensor) -> Tensor:
return values.mean(time) * 2.0
Indexing
Use selection in equations; .isel() and .sel() are not lowered in transforms.
Both select one element along a dimension and remove that dimension from the result.
| Method | Selector |
|---|---|
x.isel(dim, index) |
Zero-based integer position or symbolic scalar integer expression. Valid negative positions count from the end. |
x.sel(dim, coordinate) |
Literal coordinate, including a captured Python constant, on a bound coordinate axis. |
isel delegates bounds handling to the backend; invalid-index behaviour may differ.
sel requires a bound coordinate axis and a matching label. Public coordinate
binding is not yet available; use isel for model evaluation in the meantime.
Coordinates may be strings, integers, floats, datetime.date or
datetime.datetime; float matches allow rounding tolerance.
Coordinate axes
| API | Meaning |
|---|---|
coordinate_axis(dimension, coordinates) |
Construct an axis from iterable labels. |
CoordinateAxis(dimension, coordinates) |
Direct constructor with a coordinate tuple. |
axis.dimension, axis.coordinates, len(axis) |
Dimension, labels and length. |
Creating an axis does not bind it to a model evaluation. Coordinate binding is
not yet available through the public API. Until it is, resolve labels to integer
positions using axis.coordinates.index(label) and use isel in equations.
Intermediate values
Selection works on named intermediate ports over known dimensions. Dimensions, extents and coordinate axes must be established before calculation; Bilt cannot infer new dimensions or changed extents on the fly.
Supported tensor arithmetic and reduction/selection expressions retain tensor
methods in equations, so composed receivers such as (weights*x+y).sum(time)
can be written directly. Broadcast alignment applies before the reduction.
Subsystem port expressions such as child.x still do not expose tensor methods
directly. A child-local equation can reduce its own Tensor parameter, or a parent
can expose the port through a Tensor alias:
from bilt import Tensor, equation
@equation
def expose(x: Tensor, child: Child) -> bool:
return x == child.x
@equation
def aggregate(total: float, x: Tensor) -> bool:
return total == x.sum(time)
Here, child: Child identifies a subsystem parameter, while the parent’s
x: Tensor provides an alias on which .sum(time) can be used.
time is defined earlier in the document.
Concrete tensor methods are
model-only: calling them directly on a returned Tensor raises TypeError.
Outside models, work with t.values for numerical operations.
Conditional selection in equations
Equations can use ordinary if/elif/else to select values using scalar or
tensor comparisons. When the predicate varies over a named dimension, Bilt
selects elementwise and broadcasts the predicate and branches by dimension name.
from bilt import equation
@equation
def within_range(x: float, result: float) -> bool:
if (x > 0) & (x < 5):
selected = x
else:
selected = 0.0
return result == selected
The same equation works with a scalar or tensor x. Combine symbolic comparisons
with & (and), | (or), and ~ (not). Parenthesise each comparison:
Python's bitwise precedence differs from comparison precedence. Python's
and, or, not and chained comparisons are not supported for symbolic
predicates.
A scalar predicate with branches on the same domain remains lazy, using Python
branching or JAX lax.cond. A tensor predicate, or a scalar predicate selecting
branches with different domains, lowers to internal elementwise selection
(numpy.where / jax.numpy.where). Both branches are evaluated in that
case, even where only one contributes to the result. Avoid expressions that
fail or produce invalid intermediate values outside the selected region.
The result domain is the union of the predicate and branch domains. Both branches must have compatible physical dimensionality and absolute/relative quantity kinds. Selection does not create a smaller or partially known tensor. Inverting an equation through a conditional is unsupported.
This is equation syntax, not a public bilt.where() or Tensor.where()
API. Selection masks are internal, not independent model ports.
Errors
Import exceptions from bilt.errors.
| Exception | Meaning / remedy |
|---|---|
BiltTensorDomainError |
Missing domain, rank mismatch, absent reduction/selection dimension or non-scalar selector. Check the tensor domain and arguments. |
BiltInvalidDomainError |
Repeated dimension in a domain. |
BiltDomainBindingError |
Conflicting dimension sizes/coordinates, unbound dimension, missing coordinate axis or missing label. |
BiltDomainRegistryLockedError |
New dimension or coordinate binding attempted after dimension order was fixed. Establish bindings before calculation. |
BiltSymbolicLoweringError |
Invalid symbolic selection, such as a non-literal sel coordinate. |
BiltEquationDimensionalityError |
Incompatible dimensions/tags or an invalid unit-aware reduction. |
BiltUnitError / BiltDimensionalityError |
Missing unit or incompatible conversion. |
TypeError / AttributeError |
Concrete model-only operation, or tensor method called on a plain symbolic expression. |
NotImplementedError |
Concrete tensor arithmetic, or unsupported transform reduction form. Use direct parameter reductions in a single return expression. |