Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 11 additions & 15 deletions benchmarks/linear_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@

COORDINATE = dim("branch")
Current = typing.Annotated[QuantityTensor, CURRENT]
Voltage = typing.Annotated[Quantity | QuantityTensor, VOLTAGE]
Resistance = typing.Annotated[Quantity | QuantityTensor, RESISTANCE]
Temperature = typing.Annotated[Quantity | QuantityTensor, TEMPERATURE]
Voltage = typing.Annotated[Quantity, VOLTAGE]
Resistance = typing.Annotated[Quantity, RESISTANCE]
Temperature = typing.Annotated[Quantity, TEMPERATURE]
Heat = typing.Annotated[QuantityTensor, POWER]
Conductance = typing.Annotated[Quantity | QuantityTensor, POWER / TEMPERATURE]
ThermalResistance = typing.Annotated[Quantity | QuantityTensor, TEMPERATURE / POWER]
Conductance = typing.Annotated[Quantity, POWER / TEMPERATURE]
ThermalResistance = typing.Annotated[Quantity, TEMPERATURE / POWER]


@dataclasses.dataclass(frozen=True)
Expand Down Expand Up @@ -144,16 +144,16 @@ class Expected:
def check(self, result: object) -> None:
"""Check units, named axes, shape and the independent analytic answer."""
if self.domain.is_scalar:
if not isinstance(result, Quantity):
if not isinstance(result, Quantity) or isinstance(result, QuantityTensor):
message = f"Expected a scalar Quantity, received {type(result)}."
raise AssertionError(message)
if result.unit != self.unit:
message = f"Expected unit {self.unit}, received {result.unit}."
raise AssertionError(message)
values = np.asarray(result.value)
else:
if not isinstance(result, Tensor):
message = f"Expected a Tensor, received {type(result)}."
if not isinstance(result, QuantityTensor):
message = f"Expected a QuantityTensor, received {type(result)}."
raise AssertionError(message)
if result.domain != self.domain:
message = f"Expected domain {self.domain}, received {result.domain}."
Expand All @@ -175,7 +175,7 @@ def _electrical(case: LinearCase) -> tuple[Implementation, dict[str, object], di
else:
current_type = typing.Annotated[QuantityTensor, CURRENT, domain(COORDINATE)] if case.hinted else Current
voltage_type = (
typing.Annotated[Quantity | QuantityTensor, VOLTAGE, Domain.scalar() if case.shared else domain(COORDINATE)]
typing.Annotated[Quantity, VOLTAGE, Domain.scalar() if case.shared else domain(COORDINATE)]
if case.hinted
else Voltage
)
Expand Down Expand Up @@ -229,14 +229,10 @@ def _thermal(case: LinearCase) -> tuple[Implementation, dict[str, object], dict[
heat_type = Heat
cold_type = Temperature
else:
hot_type = (
typing.Annotated[Quantity | QuantityTensor, TEMPERATURE, domain(COORDINATE)] if case.hinted else Temperature
)
hot_type = typing.Annotated[Quantity, TEMPERATURE, domain(COORDINATE)] if case.hinted else Temperature
heat_type = typing.Annotated[QuantityTensor, POWER, domain(COORDINATE)] if case.hinted else Heat
cold_type = (
typing.Annotated[
Quantity | QuantityTensor, TEMPERATURE, Domain.scalar() if case.shared else domain(COORDINATE)
]
typing.Annotated[Quantity, TEMPERATURE, Domain.scalar() if case.shared else domain(COORDINATE)]
if case.hinted
else Temperature
)
Expand Down
285 changes: 174 additions & 111 deletions docs/api/quantity-annotations.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions docs/api/systems.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ See [Systems and values](../guide/systems-and-values.md) and
| `instance.name` | Return a known value, or calculate and cache it using the selected implementation. |

Annotations declare ports; `ClassVar` annotations are excluded.
Use dimensions on pointwise unit-aware system ports, such as `Annotated[Quantity | QuantityTensor, LENGTH]`;
see [Units](units.md). Supply known values at construction.
Use dimensions on unit-aware system ports, such as `Annotated[Quantity, LENGTH]`;
see [Quantity annotations and typing](quantity-annotations.md) and [Units](units.md). Supply known values at construction.

## Implementations

Expand Down
14 changes: 6 additions & 8 deletions docs/api/tensors.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Import tensor helpers from `bilt`. See [Domains and tensors](../guide/dimensions-domains-and-tensors.md)
for an introduction, [Units API](units.md) for physical units, and
[Quantity annotations and typing](quantity-annotations.md) for scalar/tensor system fields.
[Quantity annotations and typing](quantity-annotations.md) for choosing between `Quantity`, `QuantityTensor`, `Number` and `Tensor`.

## Construction and inspection

Expand All @@ -13,11 +13,10 @@ for an introduction, [Units API](units.md) for physical units, and
| `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. |
| `tensor(value)` / `tensor(value, unit=unit)` | 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`. |
| `t.unit` | Physical unit of a `QuantityTensor`. |
| `dimension.name` | Dimension name. |

```python exec="on" session="tensor-api"
Expand All @@ -42,8 +41,7 @@ align by name. Result axes follow the evaluation's dimension binding order.
| `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
Use `Annotated[QuantityTensor, LENGTH]` for tensor-only unit-bearing fields or equation parameters, and `Annotated[Quantity, LENGTH]` for a quantity of any shape. `Tensor` and `Number` ports are outside the physical unit system, so `Annotated[Tensor, LENGTH]` is refused. 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.
Expand All @@ -63,8 +61,8 @@ present in the operand's domain and removes it from the result's domain.

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
Reducing the last dimension gives a scalar domain. Outputs declared
`QuantityTensor` remain rank-zero tensors; other scalar-domain outputs are numerical
scalars or declared quantities.

**Transforms:** use a single return statement, applying reductions directly to
Expand Down
27 changes: 13 additions & 14 deletions docs/api/units.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Reference for `bilt.units`, `bilt.units.dimensions` and unit-related exceptions in
`bilt.errors`. For a walkthrough, see [Units in models](../guide/units.md).
For choosing scalar, tensor and pointwise field annotations, see
For choosing between the `Quantity`, `QuantityTensor`, `Number` and `Tensor` annotations, see
[Quantity annotations and typing](quantity-annotations.md).

## Imports and dimensions
Expand Down Expand Up @@ -75,13 +75,13 @@ cost_in_gbp = (100.0 * USD[2024]).convert_to(GBP[2024])

## Quantities

`Quantity` is available from both `bilt` and `bilt.units`. Methods return a new
quantity without changing the original.
`Quantity` is available from both `bilt` and `bilt.units`. It is the annotation for
any value with a unit, single or a tensor; you create a quantity by multiplying a
number by a unit. Methods return a new quantity without changing the original.

| API | Meaning |
| --- | --- |
| `Quantity(value, unit)` | Construct a scalar quantity with a numerical value and a `Unit`. |
| `5.0 * kilometer` | Shorthand for `Quantity(5.0, kilometer)`; use floating-point literals. |
| `5.0 * kilometer` | Create a quantity with a numerical value and a `Unit`. |
| `q.value` | Numerical value in `q.unit`. |
| `q.unit` | The quantity's unit; `q.unit.dimension` gives its dimension. |
| `q.convert_to(unit)` | Rescale the value (and apply absolute offsets) to a compatible unit. Dimensions, including tags, must agree. |
Expand Down Expand Up @@ -112,7 +112,7 @@ calculated outputs in coherent units. For ordinary physical dimensions these
are SI units; currency uses USD2025 and metadata tags are retained.

Inside transforms, extract numbers with `q.convert_to(unit).value` and construct
quantities with `Quantity(value, unit)` or a float multiplied by a unit. Bare
quantities by multiplying a number by a unit. Bare
quantity `.value`, representation-dependent `.unit` access, and `cast_to()` are
refused. Transform checks do not prove dimensional correctness of arbitrary Python.

Expand Down Expand Up @@ -208,13 +208,12 @@ Equations express tag changes through tagged unit factors; transforms support

## Unit-carrying tensors

Import `tensor` and `Tensor` from `bilt`.
Import `tensor` and `QuantityTensor` from `bilt`.

| API | Meaning |
| --- | --- |
| `tensor(values, *, over=None, domain=None, unit=None)` | Label array values with a unit. Non-scalar values require `over` or `domain`; provide only one. |
| `Tensor.scalar(value, unit=None)` | Construct a rank-zero tensor, optionally with a unit. |
| `t.unit`, `t.values`, `t.domain` | Unit (or `None`), numerical array, and named domain. |
| `tensor(values, *, over=None, domain=None, unit=None)` | Label array values with a unit. Non-scalar values require `over` or `domain`; provide only one. A single value without either gives a rank-zero tensor. |
| `t.unit`, `t.values`, `t.domain` | Unit, numerical array, and named domain. |
| `t.convert_to(unit)` | Convert all values, retaining the domain. Requires an existing compatible unit. |
| `t * unit` | Label an unlabelled tensor, or compose with its existing unit, without rescaling its values. |
| `t / unit` | Divide an existing tensor unit by another unit, without rescaling values. |
Expand All @@ -224,8 +223,8 @@ without one, it returns a `Tensor`. For how to annotate these values on
model fields and equations, see [Quantity annotations and typing](quantity-annotations.md).

Unit multiplication labels values; `convert_to()` rescales them. Concrete tensor
arithmetic is otherwise dispatched through Bilt models. Tensors do not expose
the quantity helpers `cast_to()` or `strip_metadata()`.
arithmetic is otherwise dispatched through Bilt models. A `QuantityTensor` also
has the quantity helpers `cast_to()` and `strip_metadata()`.

## Errors and messages

Expand All @@ -240,8 +239,8 @@ message strings; messages include the offending ports, quantities and units.
| `BiltMetadataError` | Invalid metadata, such as an empty tag. |
| `BiltEquationDimensionalityError` | An equation is dimensionally inconsistent. Check operations, constants, tags and absolute/relative quantities. |
| `BiltImplementationDimensionalityError` | Shared ports have conflicting declarations or the implementation makes an equation inconsistent. Declare the same dimension everywhere. |
| `BiltInputDimensionalityError` | An input has the wrong dimension, tags, absolute/relative kind or scalar/tensor carrier, or is unlabelled. |
| `BiltPortDeclarationError` | Invalid quantity annotation: declare a physical dimension, not a unit. Use `Quantity` or `QuantityTensor` (or their union), not dimensioned `Tensor`. This is a `BiltDefinitionError`, not a `BiltUnitsError`. |
| `BiltInputDimensionalityError` | An input has the wrong dimension, tags, absolute/relative kind, is not a tensor where `QuantityTensor` is declared, or is unlabelled. |
| `BiltPortDeclarationError` | Invalid quantity annotation: declare a physical dimension, not a unit. Use `Quantity` or `QuantityTensor`, not dimensioned `Tensor`, with `Annotated` at the top of the annotation. This is a `BiltDefinitionError`, not a `BiltUnitsError`. |
| `BiltDefinitionError` | Unsupported unit operations inside a transform, including bare quantity `.value` or `cast_to()`. |
| `BiltUnresolvedAnnotationError` | An annotation name is missing when the decorator runs. Import or define it at runtime, outside `if TYPE_CHECKING:`. |

Expand Down
49 changes: 25 additions & 24 deletions docs/guide/dimensions-domains-and-tensors.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,32 +178,33 @@ Bilt can align the values using the **names of their dimensions**, rather than r

### Scalar or tensor values at system boundaries

When a system can accept either a plain scalar or a **unitless** tensor,
a union is sufficient. There is no need for an additional Bilt protocol:
A port annotation says two things about a value: whether it carries a unit, and
whether it must be a tensor or may have any shape.

```python exec="off"
from bilt import Interface, Tensor, field, system
| | Any shape | Must be a tensor |
| ------------ | ---------- | ---------------- |
| **Units** | `Quantity` | `QuantityTensor` |
| **No units** | `Number` | `Tensor` |

When a system accepts either a plain number or a **unitless** tensor, annotate it
`Number`:

type Value = float | Tensor
```python exec="off"
from bilt import Interface, Number, field, system


@system
class Scale(metaclass=Interface):
x: Value = field()
doubled: Value = field()
x: Number = field()
doubled: Number = field()
```

Both `Scale(x=2.0)` and `Scale(x=tensor([1.0, 2.0], over=time))`
are accepted. An equation can still use `float` annotations and Bilt will
lift it over the input's named domain. This keeps the system's accepted
value types separate from the local operations of the equation.

**Limit of static typing:** The concrete `QuantityTensor` class currently
inherits `Tensor`. Python type checkers therefore also consider a
unit-bearing tensor valid wherever a `Tensor` is annotated. Bilt rejects
it **at runtime** at a plain, unitless port. A static guarantee that the
tensor has no unit would require a separate tensor typing design; a
`float | Tensor` union cannot provide that guarantee.
are accepted. An equation written for one value, with `float` or `Number`
annotations, is lifted by Bilt over the input's named domain. A tensor with a
unit is not a `Number`: type checkers reject it, and so does Bilt at runtime.
For values with units, `Annotated[Quantity, DIM]` plays the same role; see
[Quantity annotations and typing](../api/quantity-annotations.md).

### Requiring a minimum domain

Expand All @@ -214,7 +215,7 @@ complete shape of the input. For a unit-bearing tensor quantity:
import typing

from bilt import Interface, Quantity, QuantityTensor, Tensor, dim, field, system
from bilt.symbolic._domains import Domain
from bilt import Domain
from bilt.units.dimensions import MASS

time = dim("time")
Expand All @@ -236,9 +237,9 @@ Bilt checks it when values enter a system and when a computed system output
has a declared minimum domain. Domain metadata is checked by Bilt at runtime;
Python type checkers do not interpret the dimensions in `Annotated`.

This form applies to the unit-bearing `QuantityTensor` annotation. The
pointwise `Quantity | QuantityTensor` union permits scalars and therefore cannot declare a
required tensor dimension. Existing unitless `Annotated[Tensor, Domain(...)]`
This form applies to the unit-bearing `QuantityTensor` annotation. A
`Quantity` may be a single value, so it cannot declare a required tensor
dimension. Existing unitless `Annotated[Tensor, Domain(...)]`
annotations remain available as exact hints for unitless structural domain
inference. Scalar equation annotations may also use `Quantity` with
`Domain.scalar()` as an exact linear-solver hint. Dimensioned `Tensor`
Expand All @@ -256,10 +257,10 @@ possible shapes but one equation needs a specific axis:
import typing

from bilt import Quantity, QuantityTensor, equation
from bilt.symbolic._domains import Domain
from bilt import Domain
from bilt.units.dimensions import MASS

type Mass = typing.Annotated[Quantity | QuantityTensor, MASS]
type Mass = typing.Annotated[Quantity, MASS]
type TimeMass = typing.Annotated[QuantityTensor, MASS, Domain((time,))]


Expand All @@ -275,7 +276,7 @@ The `time` dimension must be present, but additional axes such as
evaluation, its domain requirement does not constrain that evaluation.

These are minimum-domain **requirements**, unlike exact `Domain` **hints**
on pointwise `Quantity | QuantityTensor` equation parameters or unitless `Tensor` parameters. In
on `Quantity` equation parameters or unitless `Tensor` parameters. In
particular, they are not passed to the linear-block inference algorithm as
exact layouts. A mismatch rejects the selected evaluation route with an
explanation naming the equation, port and missing dimensions.
Expand Down
6 changes: 3 additions & 3 deletions docs/guide/equations-and-acausal-modelling.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,13 +337,13 @@ elementwise and broadcasts the branches by dimension name. The equation itself
can still use ordinary scalar annotations:

```python exec="on" session="motion-equations"
from bilt import Tensor, dim, tensor
from bilt import Number, dim, tensor


@system
class MaskedRange(metaclass=Interface):
x: float | Tensor = field()
result: float | Tensor = field()
x: Number = field()
result: Number = field()


@equation
Expand Down
Loading
Loading