diff --git a/benchmarks/linear_models.py b/benchmarks/linear_models.py index 5413b55e..2b3a8c75 100644 --- a/benchmarks/linear_models.py +++ b/benchmarks/linear_models.py @@ -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) @@ -144,7 +144,7 @@ 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: @@ -152,8 +152,8 @@ def check(self, result: object) -> None: 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}." @@ -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 ) @@ -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 ) diff --git a/docs/api/quantity-annotations.md b/docs/api/quantity-annotations.md index 58d001a6..2d17fcd1 100644 --- a/docs/api/quantity-annotations.md +++ b/docs/api/quantity-annotations.md @@ -1,43 +1,52 @@ # Quantity annotations and typing -This is the reference for quantity annotations on Bilt system fields, equations -and transforms. For unit definitions, conversions and arithmetic, see the +This is the reference for the annotations on Bilt system fields, equations and +transforms. For unit definitions, conversions and arithmetic, see the [Units API](units.md); for a guided introduction, see [Units in models](../guide/units.md). For named axes, reductions and selections, see the [Tensor API](tensors.md). ## Choose the annotation for the job -A **system** declares which values its fields can accept. An **equation** describes -a mathematical relationship. A system field can accept either a scalar or a -tensor quantity, while a scalar-annotated equation can still operate pointwise -over tensor inputs: Bilt builds symbolic expressions and lifts the relationship -over compatible domains. +A port annotation answers two independent questions: -| Value | System field (when either shape is allowed) | Equation parameter | -| --- | --- | --- | -| Plain scalar or unitless tensor | `float | Tensor` | `float` for scalar-local arithmetic; `Tensor` for named tensor methods | -| Pointwise quantity with a physical unit | `Quantity \| QuantityTensor` | `Quantity` for scalar-local arithmetic (or the union for pointwise operators) | -| Tensor quantity with a physical unit | `QuantityTensor` | `QuantityTensor` for named tensor methods | -| Strictly scalar quantity with a physical unit | `Quantity` | `Quantity` for scalar arithmetic | +1. **Units:** does the value carry a unit? If so, `Annotated` also states its + physical dimension. +2. **Shape:** may it have any shape, or must it be a tensor because something + reduces or selects along one of its axes? -For example, a system may accept either a scalar or a tensor of mass. Named -aliases keep the system and equation declarations readable: +| | Any shape | Must be a tensor | +| ------------ | ---------- | ---------------- | +| **Units** | `Quantity` | `QuantityTensor` | +| **No units** | `Number` | `Tensor` | -```python exec="off" +All four are imported from `bilt`. They describe what a value can do, not which +class it is: you never construct them by name. Create a quantity by multiplying a +number by a unit (`2.0 * kilogram`), and a tensor with `tensor(...)`. + +An annotation means the same thing on a system field, an equation parameter and a +transform. `Quantity` accepts a scalar or a tensor everywhere: an equation or +transform written for one value is lifted by Bilt over the domain of a tensor +input. Reach for `QuantityTensor` only when the code reduces or selects along an +axis. + +## One alias per dimension + +Write the dimension once, in an alias, and use it on systems and equations alike: + +```python exec="on" session="quantity-annotations" from typing import Annotated -from bilt import Implementation, Interface, Quantity, QuantityTensor, dim, equation, field, system, tensor +from bilt import Implementation, Interface, Quantity, dim, equation, field, system, tensor from bilt.units import kilogram from bilt.units.dimensions import MASS type Mass = Annotated[Quantity, MASS] -type PointwiseMass = Annotated[Quantity | QuantityTensor, MASS] @system class DoubleMass(metaclass=Interface): - mass: PointwiseMass = field() - doubled: PointwiseMass = field() + mass: Mass = field() + doubled: Mass = field() @equation @@ -50,68 +59,119 @@ time = dim("time") with Implementation(DoubleMass, [doubling]): scalar_result = DoubleMass(mass=2.0 * kilogram).doubled tensor_result = DoubleMass(mass=tensor([2.0, 3.0], over=time, unit=kilogram)).doubled + +assert scalar_result == 4.0 * kilogram +assert tensor_result.values.tolist() == [4.0, 6.0] ``` -The equation is pointwise, so Bilt automatically lifts its scalar `Mass` annotation -when an input varies over `time`. The system's `PointwiseMass` annotation accepts -either shape; Bilt builds symbolic expressions when constructing the equation. +The same `doubling` equation serves a scalar mass and a mass that varies over +`time`. It is **pointwise**: it relates values at each point of the domain +independently, so Bilt lifts it over the tensor's domain. -## Available types +An alias can be written with the `type` statement, as here, or as a plain +assignment (`Mass = Annotated[Quantity, MASS]`); Bilt reads both the same way. -| Annotation | Type checker understands | Runtime interpretation | +## What each annotation accepts + +| Annotation | Accepts | Type checkers know | | --- | --- | --- | -| `Quantity \| QuantityTensor` | Unit-bearing scalar **or** tensor, with pointwise operators | Flexible pointwise quantity boundary and equation | -| `Quantity` | Concrete scalar `Quantity`, with its arithmetic methods | Scalar quantity arithmetic; lifted inside equations | -| `QuantityTensor` | Concrete unit-bearing tensor, including tensor methods | Tensor quantity with a non-optional unit | -| `Tensor` | Tensor with or without a unit | Plain `Tensor` system fields are unitless; use `QuantityTensor` for dimensioned tensors | -| `float | Tensor` | Plain scalar or tensor | Unitless system boundary | +| `Annotated[Quantity, DIM]` | A scalar quantity or a tensor of quantities with that dimension | Quantity arithmetic, `unit`, `value`, `convert_to`, `cast_to`, `strip_metadata`, comparisons | +| `Annotated[QuantityTensor, DIM]` | A tensor of quantities with that dimension | All of the above, plus `domain`, `values`, `sum`, `mean`, `min`, `max`, `prod`, `isel`, `sel` | +| `Number` | A plain number or a unitless tensor | Plain arithmetic | +| `Tensor` | A unitless tensor | Plain arithmetic and the named tensor methods | +| `float` | A plain number; Bilt also accepts a unitless tensor, but type checkers do not | Ordinary `float` | + +Prefer `Number` to `float` for a plain port that may receive a tensor. Inside an +equation or transform the two behave alike, since Bilt lifts the relationship +over a tensor input either way. + +`Number` and `Tensor` are for values **outside** the unit system: counts, +flags, inputs to external code. A coefficient that takes part in quantity +arithmetic, such as a gain multiplying a length in an equation, must be a +dimensionless quantity, `Annotated[Quantity, DIMENSIONLESS]`, supplied as +`0.5 * UNITLESS`. + +A `QuantityTensor` is also a `Quantity`, so it can be passed wherever a +`Quantity` is expected. Neither quantity annotation accepts a unitless value, +and neither `Number` nor `Tensor` accepts a value with a unit: type checkers +report these mistakes, and Bilt rejects them at runtime too. + +`Quantity` does not distinguish a scalar from a tensor. Its `value` is therefore +a `Number`: a `float` for a scalar, a unitless `Tensor` for a tensor. A transform +that returns a quantity's magnitude is annotated `-> Number`: + +```python exec="off" +from bilt import Number, transform +from bilt.units import gram -Use `Quantity | QuantityTensor` for pointwise quantities that may be scalar or tensor. Use `Quantity` for scalar-only inputs and operations, and `QuantityTensor` when named tensor methods are required. In longer models, use paired aliases such as `Mass = Annotated[Quantity, MASS]` and `PointwiseMass = Annotated[Quantity | QuantityTensor, MASS]` instead of repeating the full annotations. -A unit-bearing tensor can be constructed with `tensor(..., unit=kilogram)`. -The factory returns `QuantityTensor` when a non-optional `Unit` is supplied -and returns `Tensor` if the unit is omitted. If the unit argument has -type `Unit | None`, the conservative static return type is `Tensor` -although the runtime object will be a `QuantityTensor` when the unit is present. +@transform +def grams(mass: Mass) -> Number: + return mass.convert_to(gram).value +``` -## Named tensor operations in equations +To get a Python `float` from a result you know is a scalar, call `float(...)` +on its value; this also works for a tensor with no dimensions. -Annotate an equation parameter as `QuantityTensor` when the equation -uses `sum`, `mean`, `isel`, `sel`, or other named tensor methods. +```python exec="on" session="quantity-annotations" +assert float(scalar_result.value) == 4.0 +``` -```python exec="off" -from typing import Annotated +## Creating values -from bilt import Quantity, QuantityTensor, dim, equation -from bilt.units.dimensions import MASS +| Expression | Annotation it satisfies | +| --- | --- | +| `2.0 * kilogram` | `Quantity` | +| `tensor([1.0, 2.0], over=time, unit=kilogram)` | `QuantityTensor` | +| `tensor([1.0, 2.0], over=time)` | `Tensor` | +| `tensor([1.0, 2.0], over=time) * kilogram` | `QuantityTensor` | -time = dim("time") -type ScalarMass = Annotated[Quantity, MASS] -type TensorMass = Annotated[QuantityTensor, MASS] +If the `unit` argument of `tensor(...)` has type `Unit | None`, the static return +type is `Tensor | QuantityTensor`. + +You can check what you were given with `isinstance`, against the same names: + +```python exec="on" session="quantity-annotations" +from bilt import QuantityTensor, Tensor + +assert isinstance(scalar_result, Quantity) +assert not isinstance(scalar_result, QuantityTensor) +assert isinstance(tensor_result, QuantityTensor) +assert not isinstance(tensor([1.0], over=time), Quantity) +assert isinstance(tensor([1.0], over=time), Tensor) +``` + +`isinstance` is looser than a port: it only checks that the methods exist, so a +`QuantityTensor` also passes `isinstance(value, Tensor)`, although a `Tensor` +port refuses it. To test for a tensor of quantities, check `QuantityTensor`. + +## Named tensor operations in equations + +Annotate an equation parameter `QuantityTensor` when the equation uses `sum`, +`mean`, `isel`, `sel` or another named tensor method: + +```python exec="on" session="quantity-annotations" +type MassOverADomain = Annotated[QuantityTensor, MASS] @equation -def total_mass(masses: TensorMass, total: ScalarMass) -> bool: +def total_mass(masses: MassOverADomain, total: Mass) -> bool: return total == masses.sum(time) ``` -A tensor with domain `(scenario, time)` can be reduced over `time`; -the result retains `scenario`. The compiler determines the resulting -domain and physical dimension. The concrete `Tensor` method return -annotations do not encode the remaining domain statically. +The result of `masses.sum(time)` is still a `QuantityTensor` to a type checker, +which a `Mass` (any shape) accepts. A tensor with domain `(scenario, time)` +reduced over `time` keeps `scenario`; Bilt determines the remaining domain and the +physical dimension when it compiles the model. The type checker does not track +which axes remain. ## Minimum domain requirements -A dimensioned tensor quantity port may require one or more named axes: +A tensor quantity port may require one or more named axes: -```python exec="off" -from typing import Annotated +```python exec="on" session="quantity-annotations" +from bilt import Domain -from bilt import QuantityTensor, dim -from bilt.symbolic._domains import Domain -from bilt.units.dimensions import MASS - -time = dim("time") type TimeMass = Annotated[QuantityTensor, MASS, Domain((time,))] ``` @@ -125,61 +185,64 @@ This declares a **minimum** domain, not an exact shape: | `(scenario,)` | No | | `()` | No | -Minimum-domain checking applies to `QuantityTensor` annotations carrying a physical dimension. At a system boundary, Bilt checks supplied and computed values. -Within an implementation, Bilt checks the requirements on **selected** -equations against the inferred domains of the values those equations use -or produce. Requirements on equations that are not selected do not -constrain that evaluation. - -`Annotated[Quantity, DIM, Domain(...)]` and -`Annotated[Quantity | QuantityTensor, DIM, Domain(...)]` remain **exact equation** -domain hints for structural/linear-block analysis. It is not a system-field -annotation, and is not reinterpreted as a minimum-domain requirement. -Dimensioned `Annotated[Tensor, DIM]` declarations are no longer supported; -use `QuantityTensor` for tensor-only fields and equations. -Domain constraints in `Annotated` are validated by Bilt, not statically -interpreted by ty or Pyrefly. +At a system boundary, Bilt checks supplied and computed values. Within an +implementation, Bilt checks the requirements on **selected** equations against the +inferred domains of the values those equations use or produce. Requirements on +equations that are not selected do not constrain that evaluation. + +On an equation parameter, `Annotated[Quantity, DIM, Domain(...)]` is an **exact** +domain hint for structural and linear-block analysis, not a minimum-domain +requirement. It is not allowed on a system field. Domain constraints are checked +by Bilt, not by type checkers. + +## Where Bilt reads an annotation + +Bilt reads the dimension, `ABSOLUTE` and any `Domain` from `Annotated` at the top +of a port's annotation, directly or through a type alias without type parameters. +Anything else raises `BiltPortDeclarationError` rather than silently ignoring the +dimension: + +- a union such as `Annotated[Quantity, MASS] | None`; +- a subscripted generic alias such as `Length[Quantity]`, where + `type Length[Q] = Annotated[Q, LENGTH]`; +- a dimension on a unitless annotation, such as `Annotated[Tensor, MASS]`: use + `QuantityTensor`. ## Symbolic and eager arithmetic -`Quantity | QuantityTensor` is useful both for a flexible **system field** -and for a **pointwise equation**. An `@equation` builds a symbolic expression -tree: pointwise operators are then lifted across compatible scalar and tensor -domains. It does **not** execute the concrete `QuantityTensor` methods. - -Outside equations, concrete `Quantity` objects support scalar arithmetic. -Concrete `Tensor` and `QuantityTensor` objects deliberately do not support -general eager arithmetic or named reductions. Arithmetic raises -`NotImplementedError`, while symbolic-only tensor methods raise `TypeError`. -`@transform` is ordinary executable Python and must not use these as eager -numerical operations. - -Python's type checkers cannot infer symbolic execution from `@equation`. -They can accept `value * 2.0` where `value` has the union type, **even -outside an equation**. This is a documented limitation of the static type -contract, not evidence that eager tensor multiplication is supported. A -future separate equation checker might detect this, but isn't part of the -quantity typing migration. - -`Quantity(value, unit)` remains the concrete scalar constructor. -For dimensioned pointwise fields, use `Quantity | QuantityTensor`. -Strict scalar fields use `Quantity`, and tensor-only fields use `QuantityTensor`. -Dimensioned `Annotated[Tensor, DIM]` declarations are rejected at system -boundaries; scalar-only equations and transforms may also use concrete `Quantity`. - -## Other limitations - -- A `float | Tensor` system field accepts scalar or unitless tensor - values. `QuantityTensor` subclasses `Tensor`, so ty and Pyrefly - cannot reject unit-bearing tensors for this union; Bilt rejects those - values at runtime. A separate tensor-typing design would be needed to - express unitless tensors statically. -- Static type checkers do not prove physical dimensions, unit categories, - named axis sets, or Bilt's structural execution choices. These are - Bilt runtime and compiler checks. -- Bilt retains the existing distinction between symbolic tensor methods - inside equations and concrete tensor operations outside a model. The - latter do not offer general eager tensor arithmetic. +An `@equation` builds a symbolic expression: Bilt calls it with symbols, not +values, and lifts pointwise operations over compatible domains. A `@transform` body +is compiled for the selected backend. In both, a parameter annotated with one of +the four types supports the operations listed above. + +Outside a model, a scalar quantity supports ordinary arithmetic and comparison. +Concrete tensors deliberately do not: arithmetic on them raises +`NotImplementedError`, and named tensor methods raise `TypeError`. Type checkers +cannot tell whether code runs inside a model, so they accept +`tensor_value * 2.0` anywhere; this is a limitation of static typing, not a sign +that eager tensor arithmetic is supported. + +## Earlier spellings + +Earlier versions of Bilt used `Quantity | QuantityTensor` for a quantity of any +shape and `float | Tensor` for a plain value of any shape, with separate aliases +such as `PointwiseMass` for system fields. `Quantity | QuantityTensor` still means +the same as `Quantity`, and `float | Tensor` is exactly `Number`, so existing +annotations keep working. Two things changed: + +- `Annotated[Quantity, DIM]` on a system field used to accept only a scalar; it now + accepts a tensor too. There is no scalar-only quantity annotation. +- `Quantity(value, unit)` no longer constructs a quantity; write `value * unit`. + +## Limitations + +- Type checkers do not prove physical dimensions, unit categories, named axis sets + or Bilt's structural execution choices. Bilt checks these when it builds and + evaluates a model. +- A `Number` must be a `float`, an `int` or a unitless tensor; Python's other + numeric types are not accepted. +- Bilt does not ship per-dimension aliases such as `Length`; define the ones a model + needs. Use the [Domains and tensors guide](../guide/dimensions-domains-and-tensors.md) for broadcasting, axis alignment and examples of domain inference. diff --git a/docs/api/systems.md b/docs/api/systems.md index a414f74b..46d7906f 100644 --- a/docs/api/systems.md +++ b/docs/api/systems.md @@ -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 diff --git a/docs/api/tensors.md b/docs/api/tensors.md index 75adb5f4..aedf3be7 100644 --- a/docs/api/tensors.md +++ b/docs/api/tensors.md @@ -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 @@ -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" @@ -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. @@ -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 diff --git a/docs/api/units.md b/docs/api/units.md index 739b62ce..2bdd5964 100644 --- a/docs/api/units.md +++ b/docs/api/units.md @@ -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 @@ -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. | @@ -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. @@ -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. | @@ -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 @@ -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:`. | diff --git a/docs/guide/dimensions-domains-and-tensors.md b/docs/guide/dimensions-domains-and-tensors.md index 2e2b9ae1..0ee35bab 100644 --- a/docs/guide/dimensions-domains-and-tensors.md +++ b/docs/guide/dimensions-domains-and-tensors.md @@ -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 @@ -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") @@ -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` @@ -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,))] @@ -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. diff --git a/docs/guide/equations-and-acausal-modelling.md b/docs/guide/equations-and-acausal-modelling.md index 9b290ada..a45af026 100644 --- a/docs/guide/equations-and-acausal-modelling.md +++ b/docs/guide/equations-and-acausal-modelling.md @@ -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 diff --git a/docs/guide/units.md b/docs/guide/units.md index 118f70de..66a33a09 100644 --- a/docs/guide/units.md +++ b/docs/guide/units.md @@ -1,7 +1,7 @@ ## Units in models For a catalogue of built-in units, helpers and errors, see the [Units API reference](../api/units.md). -For flexible unit-bearing scalar/tensor fields and equation annotations, see +For the full set of annotations (`Quantity`, `QuantityTensor`, `Number` and `Tensor`), see [Quantity annotations and typing](../api/quantity-annotations.md). So far, the values in our models have mostly been plain numbers: @@ -23,20 +23,13 @@ Bilt lets us put that information into the model. We will start with the motion First, let's make a quantity: ```python exec="on" session="units-models" -from bilt import Quantity from bilt.units import kilometer, meter distance = 5.0 * kilometer ``` -A **quantity** combines a numerical value with a unit. We can also construct one explicitly: - -```python exec="on" session="units-models" -distance = Quantity(5.0, kilometer) -``` - -Both expressions describe the same distance. +A **quantity** combines a numerical value with a unit. Multiplying a number by a unit is how we create one. To express it in another unit, use `convert_to()`: @@ -68,32 +61,29 @@ Let's declare our motion system again: ```python exec="on" session="units-models" from typing import Annotated -from bilt import Implementation, Interface, Quantity, QuantityTensor, equation, field, system, transform +from bilt import Implementation, Interface, Quantity, equation, field, system, transform from bilt.units.dimensions import LENGTH, TIME Length = Annotated[Quantity, LENGTH] Duration = Annotated[Quantity, TIME] Speed = Annotated[Quantity, LENGTH / TIME] -PointwiseLength = Annotated[Quantity | QuantityTensor, LENGTH] -PointwiseDuration = Annotated[Quantity | QuantityTensor, TIME] -PointwiseSpeed = Annotated[Quantity | QuantityTensor, LENGTH / TIME] @system class Motion(metaclass=Interface): - distance: PointwiseLength = field() - speed: PointwiseSpeed = field() - duration: PointwiseDuration = field() + distance: Length = field() + speed: Speed = field() + duration: Duration = field() ``` There is one new piece of Python here: ```python exec="on" session="units-models" -Annotated[Quantity | QuantityTensor, LENGTH] +Annotated[Quantity, LENGTH] ``` -`Annotated` attaches a physical dimension to a Python type. The union accepts a scalar `Quantity` or a unit-bearing `QuantityTensor`, and `LENGTH` states what the quantity measures. +`Annotated` attaches a physical dimension to a Python type. `Quantity` says the value carries a unit, and `LENGTH` states what the quantity measures. Bilt reads that annotation when `@system` runs. The `distance` field now says: @@ -101,18 +91,17 @@ Bilt reads that annotation when `@system` runs. The `distance` field now says: It does not prescribe metres or kilometres. -System fields use `Pointwise...` aliases because they accept scalar or tensor quantities. Equations and transforms retain shorter scalar aliases (`Length`, `Speed`, and `Duration`); Bilt lifts equations over compatible tensor domains. +A `Quantity` may be a single value or a tensor of values; we will meet tensors [later in this guide](#quantities-can-vary-over-a-domain). The same aliases serve the system and, below, its equation. Dimensions can be combined using multiplication, division and powers. Speed is length divided by time. Acceleration would be `LENGTH / TIME**2`. Use a dimension in the annotation, rather than a unit: ```python exec="on" session="units-models" -Length = Annotated[Quantity, LENGTH] # Scalar equation or transform. -PointwiseLength = Annotated[Quantity | QuantityTensor, LENGTH] # Scalar or tensor field. +Length = Annotated[Quantity, LENGTH] ``` -`Annotated[Quantity | QuantityTensor, meter]` raises `BiltPortDeclarationError`, because `meter` is a unit rather than a dimension. Quantity annotations also need a physical dimension. Use `Annotated[Quantity, LENGTH]` for scalar-only fields, `Annotated[QuantityTensor, LENGTH]` for tensor-only fields, or `Annotated[Quantity | QuantityTensor, LENGTH]` for fields accepting either. +`Annotated[Quantity, meter]` raises `BiltPortDeclarationError`, because `meter` is a unit rather than a dimension. A `Quantity` annotation also needs a physical dimension. ### Give the equation the same dimensions @@ -216,10 +205,10 @@ Extend the system with one field: ```python exec="off" @system class Motion(metaclass=Interface): - distance: PointwiseLength = field() - speed: PointwiseSpeed = field() - duration: PointwiseDuration = field() - allowance: PointwiseLength = field() + distance: Length = field() + speed: Speed = field() + duration: Duration = field() + allowance: Length = field() @transform @@ -241,17 +230,7 @@ with motion_model: assert result == 1500.0 * meter ``` -The constant means five hundred metres regardless of the unit used by the caller. - -Quantity constructors work too: - -```python exec="off" -@transform -def allowance(distance: Length) -> Length: - return distance + Quantity(0.5, kilometer) -``` - -This describes the same calculation. +The constant means five hundred metres regardless of the unit used by the caller. Writing `distance + 0.5 * kilometer` describes the same calculation. Bilt translates the unit operations in a transform into numerical operations for the backend. The backend computes with coherent values, while the model keeps its declarations at the boundary. @@ -262,21 +241,24 @@ That is also why the output comes back in metres. Returning a quantity expressed Sometimes another library wants a plain number in a particular unit. We can make that conversion explicit: ```python exec="off" +from bilt import Number + + @transform -def distance_km(distance: Length) -> float: +def distance_km(distance: Length) -> Number: return distance.convert_to(kilometer).value ``` -For a distance of one thousand metres, this produces `1.0`. +For a distance of one thousand metres, this produces `1.0`. The output is a `Number`, a plain value of any shape, because `distance` may be a tensor of lengths; the transform then produces a tensor of plain numbers. -Add `distance_km: float = field()` to the interface and include the transform in its implementation to expose that result through a system. +Add `distance_km: Number = field()` to the interface and include the transform in its implementation to expose that result through a system. The opposite bridge is just as explicit: ```python exec="off" @transform def distance(distance_km: float) -> Length: - return Quantity(distance_km, kilometer) + return distance_km * kilometer ``` This interprets a plain number as kilometres and produces a declared length. These two transforms illustrate opposite directions; use the one needed by the surrounding model. @@ -327,17 +309,16 @@ from bilt.units.dimensions import DIMENSIONLESS Ratio = Annotated[Quantity, DIMENSIONLESS] -PointwiseRatio = Annotated[Quantity | QuantityTensor, DIMENSIONLESS] half = 50.0 * percent assert half.convert_to(UNITLESS).value == 0.5 ``` -A dimensionless system field still requires a quantity, such as `Quantity(0.5, UNITLESS)`; a bare `0.5` is refused. For fields accepting either shape, use `PointwiseRatio`; `Ratio` remains the scalar annotation for equations and transforms. +A dimensionless system field still requires a quantity, such as `0.5 * UNITLESS`; a bare `0.5` is refused. `DIMENSIONLESS` is the dimension used in declarations. `UNITLESS` is a unit used to construct or convert quantities. -In equations, plain ports cannot participate in the same quantity arithmetic as declared ports. If a gain multiplies a length, declare the gain as `Ratio` too. Numerical literals such as the `2.0` in `distance * 2.0` can still act as ordinary scaling constants. +In equations, plain ports (`float` or `Number`) cannot participate in the same quantity arithmetic as declared ports. If a gain multiplies a length, declare the gain as `Ratio` too, and supply it as a quantity such as `0.5 * UNITLESS`. Numerical literals such as the `2.0` in `distance * 2.0` can still act as ordinary scaling constants. Transforms can bridge between plain values and quantities explicitly, as we did with `distance_km`. @@ -373,22 +354,19 @@ A reading of twenty degrees Celsius is a position on a temperature scale. A rise Bilt represents these as **absolute** and **relative** quantities: ```python exec="on" session="units-models" -from bilt import Quantity, QuantityTensor from bilt.units import absolute_celsius, absolute_kelvin, celsius, kelvin from bilt.units.dimensions import ABSOLUTE, TEMPERATURE AbsoluteTemperature = Annotated[Quantity, TEMPERATURE, ABSOLUTE] TemperatureChange = Annotated[Quantity, TEMPERATURE] -PointwiseAbsoluteTemperature = Annotated[Quantity | QuantityTensor, TEMPERATURE, ABSOLUTE] -PointwiseTemperatureChange = Annotated[Quantity | QuantityTensor, TEMPERATURE] @system class Heater(metaclass=Interface): - inlet: PointwiseAbsoluteTemperature = field() - rise: PointwiseTemperatureChange = field() - outlet: PointwiseAbsoluteTemperature = field() + inlet: AbsoluteTemperature = field() + rise: TemperatureChange = field() + outlet: AbsoluteTemperature = field() @equation @@ -402,7 +380,7 @@ def heating( with Implementation(Heater, [heating]): outlet = Heater( - inlet=Quantity(20.0, absolute_celsius), + inlet=20.0 * absolute_celsius, rise=10.0 * celsius, ).outlet @@ -432,30 +410,29 @@ return midpoint == cold + (hot - cold) / 2.0 The difference is relative; adding half of it to `cold` produces an absolute reading. -In a transform that receives a plain Celsius number, construct the reading explicitly with `Quantity(degrees, absolute_celsius)`. To extract Celsius degrees from an absolute quantity, use `reading.convert_to(absolute_celsius).value`. +In a transform that receives a plain Celsius number, multiply it by the absolute unit, as in `degrees * absolute_celsius`, to read it as an absolute temperature. To extract Celsius degrees from an absolute quantity, use `reading.convert_to(absolute_celsius).value`. `celsius` denotes a change; `absolute_celsius` denotes a reading. They cannot be substituted for each other at a declared port. ### Quantities can vary over a domain -Units also work with the tensors introduced in [Domains and tensors](dimensions-domains-and-tensors.md): +Units also work with the tensors introduced in [Domains and tensors](dimensions-domains-and-tensors.md). The `Length` alias we already have accepts a tensor of lengths: ```python exec="on" session="units-models" -from bilt import QuantityTensor, dim, tensor +from bilt import dim, tensor -LengthTensor = Annotated[QuantityTensor, LENGTH] sample = dim("sample") @system class Survey(metaclass=Interface): - distance: LengthTensor = field() - doubled: LengthTensor = field() + distance: Length = field() + doubled: Length = field() @equation -def doubling(doubled: LengthTensor, distance: LengthTensor) -> bool: +def doubling(doubled: Length, distance: Length) -> bool: return doubled == distance * 2.0 @@ -473,9 +450,9 @@ The domain says where the value varies. The unit says what its numbers represent These are independent: `dim("sample")` names an array axis, while `LENGTH` describes a physical dimension. -Use `Annotated[QuantityTensor, LENGTH]` when a field or equation needs a tensor quantity. It rejects scalar quantities. For pointwise fields and equations accepting both, use `Annotated[Quantity | QuantityTensor, LENGTH]`. Named tensor operations still need `QuantityTensor`. +`Annotated[Quantity, LENGTH]` accepts a single length or a tensor of lengths. Use `Annotated[QuantityTensor, LENGTH]` when a field or equation needs a tensor, for example because it sums or selects along an axis; it rejects single quantities. -A tensor with no domain axes—a rank-zero tensor—is still a tensor. For example, `tensor(1.0, unit=kilometer)` is accepted by a tensor-quantity length field. Calculated outputs from tensor-quantity fields remain tensors even when their domain is scalar. They can therefore be reused as inputs without changing their declared type. +A tensor with no domain axes—a rank-zero tensor—is still a tensor. For example, `tensor(1.0, unit=kilometer)` is accepted by an `Annotated[QuantityTensor, LENGTH]` field. Calculated outputs declared `QuantityTensor` remain tensors even when their domain is scalar. They can therefore be reused as inputs without changing their declared type. ### Tags preserve what a quantity measures @@ -484,7 +461,6 @@ Sometimes physical dimensions alone are insufficient. A kilogram of fuel and a k Bilt's metadata tags can make that distinction part of the declaration: ```python exec="on" session="units-models" -from bilt import Quantity, QuantityTensor from bilt.units import Metadata, kilogram @@ -497,8 +473,8 @@ Co2Mass = Annotated[Quantity, MASS * co2] @system class Burn(metaclass=Interface): - burned: Annotated[Quantity | QuantityTensor, MASS * fuel] = field() - emitted: Annotated[Quantity | QuantityTensor, MASS * co2] = field() + burned: FuelMass = field() + emitted: Co2Mass = field() @equation @@ -527,7 +503,7 @@ The errors identify the stage at which Bilt finds a disagreement: | Error | What to check | | --- | --- | -| `BiltPortDeclarationError` | Use exactly one physical dimension on a quantity declaration. For new code, use `Quantity`, `QuantityTensor`, or their union, and annotate with a dimension rather than a unit. | +| `BiltPortDeclarationError` | Use exactly one physical dimension on a `Quantity` or `QuantityTensor` declaration, at the top of the annotation, and annotate with a dimension rather than a unit. | | `BiltEquationDimensionalityError` | Check the equation's operations, both sides of the relation, and absolute versus relative quantities. | | `BiltImplementationDimensionalityError` | Give every occurrence of a shared port the same declaration. | | `BiltInputDimensionalityError` | Supply a quantity or tensor with the required dimension, tags and absolute or relative unit. | diff --git a/docs/worked_examples/battery-electric-mission-model-with-quasi-monte-carlo-broadcasting.md b/docs/worked_examples/battery-electric-mission-model-with-quasi-monte-carlo-broadcasting.md index 77b7b790..6b516937 100644 --- a/docs/worked_examples/battery-electric-mission-model-with-quasi-monte-carlo-broadcasting.md +++ b/docs/worked_examples/battery-electric-mission-model-with-quasi-monte-carlo-broadcasting.md @@ -92,7 +92,7 @@ Each transform describes one scalar engineering relationship. Nothing in these f ```python exec="off" from typing import Annotated -from bilt import Implementation, Interface, Quantity, QuantityTensor, field, system, transform +from bilt import Implementation, Interface, Quantity, field, system, transform from bilt.units.dimensions import DIMENSIONLESS, ENERGY, LENGTH, MASS @@ -103,33 +103,26 @@ SpecificEnergy = Annotated[Quantity, ENERGY / MASS] EnergyIntensity = Annotated[Quantity, ENERGY / (LENGTH * MASS)] Ratio = Annotated[Quantity, DIMENSIONLESS] -PointwiseSpecificEnergy = Annotated[Quantity | QuantityTensor, ENERGY / MASS] -PointwiseRatio = Annotated[Quantity | QuantityTensor, DIMENSIONLESS] -PointwiseLength = Annotated[Quantity | QuantityTensor, LENGTH] -PointwiseMass = Annotated[Quantity | QuantityTensor, MASS] -PointwiseEnergyIntensity = Annotated[Quantity | QuantityTensor, ENERGY / (LENGTH * MASS)] -PointwiseEnergy = Annotated[Quantity | QuantityTensor, ENERGY] - @system class Mission(metaclass=Interface): - specific_energy: PointwiseSpecificEnergy = field() - propulsive_efficiency: PointwiseRatio = field() - energy_multiplier: PointwiseRatio = field() + specific_energy: SpecificEnergy = field() + propulsive_efficiency: Ratio = field() + energy_multiplier: Ratio = field() - distance: PointwiseLength = field() - payload: PointwiseMass = field() + distance: Length = field() + payload: Mass = field() - empty_mass: PointwiseMass = field() - energy_intensity: PointwiseEnergyIntensity = field() - usable_fraction: PointwiseRatio = field() - max_battery_mass: PointwiseMass = field() + empty_mass: Mass = field() + energy_intensity: EnergyIntensity = field() + usable_fraction: Ratio = field() + max_battery_mass: Mass = field() - gross_mass: PointwiseMass = field() - shaft_energy: PointwiseEnergy = field() - electrical_energy: PointwiseEnergy = field() - battery_mass: PointwiseMass = field() - battery_margin: PointwiseMass = field() + gross_mass: Mass = field() + shaft_energy: Energy = field() + electrical_energy: Energy = field() + battery_mass: Mass = field() + battery_margin: Mass = field() @transform @@ -178,7 +171,7 @@ mission_model = Implementation( ) ``` -The named `Pointwise...` aliases allow the system fields to accept scalar or tensor quantities, while the shorter scalar aliases remain appropriate for the transforms. +Each alias, such as `Mass = Annotated[Quantity, MASS]`, accepts a single quantity or a tensor of quantities, so the same aliases serve the system fields and the transforms. The model above is ordinary displayed Python. For this documentation build, the same definitions are loaded from a temporary Python module. This is only needed because Bilt currently obtains transform source using `inspect.getsource()`, while `markdown-exec` normally defines functions dynamically. @@ -186,7 +179,7 @@ The model above is ordinary displayed Python. For this documentation build, the model_source = """ from typing import Annotated -from bilt import Implementation, Interface, Quantity, QuantityTensor, field, system, transform +from bilt import Implementation, Interface, Quantity, field, system, transform from bilt.units.dimensions import DIMENSIONLESS, ENERGY, LENGTH, MASS @@ -197,33 +190,27 @@ SpecificEnergy = Annotated[Quantity, ENERGY / MASS] EnergyIntensity = Annotated[Quantity, ENERGY / (LENGTH * MASS)] Ratio = Annotated[Quantity, DIMENSIONLESS] -PointwiseSpecificEnergy = Annotated[Quantity | QuantityTensor, ENERGY / MASS] -PointwiseRatio = Annotated[Quantity | QuantityTensor, DIMENSIONLESS] -PointwiseLength = Annotated[Quantity | QuantityTensor, LENGTH] -PointwiseMass = Annotated[Quantity | QuantityTensor, MASS] -PointwiseEnergyIntensity = Annotated[Quantity | QuantityTensor, ENERGY / (LENGTH * MASS)] -PointwiseEnergy = Annotated[Quantity | QuantityTensor, ENERGY] @system class Mission(metaclass=Interface): - specific_energy: PointwiseSpecificEnergy = field() - propulsive_efficiency: PointwiseRatio = field() - energy_multiplier: PointwiseRatio = field() + specific_energy: SpecificEnergy = field() + propulsive_efficiency: Ratio = field() + energy_multiplier: Ratio = field() - distance: PointwiseLength = field() - payload: PointwiseMass = field() + distance: Length = field() + payload: Mass = field() - empty_mass: PointwiseMass = field() - energy_intensity: PointwiseEnergyIntensity = field() - usable_fraction: PointwiseRatio = field() - max_battery_mass: PointwiseMass = field() + empty_mass: Mass = field() + energy_intensity: EnergyIntensity = field() + usable_fraction: Ratio = field() + max_battery_mass: Mass = field() - gross_mass: PointwiseMass = field() - shaft_energy: PointwiseEnergy = field() - electrical_energy: PointwiseEnergy = field() - battery_mass: PointwiseMass = field() - battery_margin: PointwiseMass = field() + gross_mass: Mass = field() + shaft_energy: Energy = field() + electrical_energy: Energy = field() + battery_mass: Mass = field() + battery_margin: Mass = field() @transform @@ -432,7 +419,7 @@ mission = Mission( ), empty_mass=20.0 * tonne, energy_intensity=0.18 * kilowatthour / (kilometer * tonne), - usable_fraction=Quantity(0.85, UNITLESS), + usable_fraction=0.85 * UNITLESS, max_battery_mass=7.5 * tonne, ) ``` @@ -666,7 +653,7 @@ mission = Mission( # ... other inputs ... empty_mass=20.0 * tonne, energy_intensity=0.18 * kilowatthour / (kilometer * tonne), - usable_fraction=Quantity(0.85, UNITLESS), + usable_fraction=0.85 * UNITLESS, max_battery_mass=7.5 * tonne, ) ``` diff --git a/docs/worked_examples/compiling-a-bilt-model-with-JAX.md b/docs/worked_examples/compiling-a-bilt-model-with-JAX.md index e1056ce9..a9b6f07f 100644 --- a/docs/worked_examples/compiling-a-bilt-model-with-JAX.md +++ b/docs/worked_examples/compiling-a-bilt-model-with-JAX.md @@ -88,8 +88,8 @@ def induced_drag( return dynamic_pressure * wing_area * induced_drag_factor * lift_coefficient**2 ``` -The system uses named pointwise aliases such as `PointwiseRatio` for fields accepting -scalar or tensor quantities, and scalar aliases such as `Ratio` for transforms. +The system fields and the transforms share one alias per dimension, such as +`Ratio`; each accepts a single quantity or a tensor of quantities. The transforms lift over compatible tensor domains, so the model does not prescribe the shape of the ensemble. Efficiencies, Mach number, aerodynamic coefficients, and emission indices are dimensionless quantities supplied with `UNITLESS`. @@ -128,7 +128,6 @@ _model_source = ( # markdown-exec: hide " Implementation,", # markdown-exec: hide " Interface,", # markdown-exec: hide " Quantity,", # markdown-exec: hide - " QuantityTensor,", # markdown-exec: hide " field,", # markdown-exec: hide " system,", # markdown-exec: hide " transform,", # markdown-exec: hide @@ -153,69 +152,57 @@ _model_source = ( # markdown-exec: hide "Power = Annotated[Quantity, ENERGY / TIME]", # markdown-exec: hide "MassRate = Annotated[Quantity, MASS / TIME]", # markdown-exec: hide "Ratio = Annotated[Quantity, DIMENSIONLESS]", # markdown-exec: hide - "PointwiseLength = Annotated[Quantity | QuantityTensor, LENGTH]", # markdown-exec: hide - "PointwiseRatio = Annotated[Quantity | QuantityTensor, DIMENSIONLESS]", # markdown-exec: hide - "PointwiseMass = Annotated[Quantity | QuantityTensor, MASS]", # markdown-exec: hide - "PointwiseTemperatureChange = Annotated[Quantity | QuantityTensor, TEMPERATURE]", # markdown-exec: hide - "PointwiseArea = Annotated[Quantity | QuantityTensor, LENGTH**2]", # markdown-exec: hide - "PointwiseAbsoluteTemperature = Annotated[Quantity | QuantityTensor, TEMPERATURE, ABSOLUTE]", # markdown-exec: hide - "PointwisePressure = Annotated[Quantity | QuantityTensor, FORCE / LENGTH**2]", # markdown-exec: hide - "PointwiseDensity = Annotated[Quantity | QuantityTensor, MASS / LENGTH**3]", # markdown-exec: hide - "PointwiseSpeed = Annotated[Quantity | QuantityTensor, LENGTH / TIME]", # markdown-exec: hide - "PointwiseForce = Annotated[Quantity | QuantityTensor, FORCE]", # markdown-exec: hide - "PointwisePower = Annotated[Quantity | QuantityTensor, ENERGY / TIME]", # markdown-exec: hide - "PointwiseMassRate = Annotated[Quantity | QuantityTensor, MASS / TIME]", # markdown-exec: hide "", # markdown-exec: hide "", # markdown-exec: hide "@system", # markdown-exec: hide "class CruiseImpact(metaclass=Interface):", # markdown-exec: hide " # Inputs", # markdown-exec: hide - " altitude: PointwiseLength = field()", # markdown-exec: hide - " mach: PointwiseRatio = field()", # markdown-exec: hide - " mass: PointwiseMass = field()", # markdown-exec: hide - " temperature_offset: PointwiseTemperatureChange = field()", # markdown-exec: hide - " wing_area: PointwiseArea = field()", # markdown-exec: hide - " zero_lift_drag_coefficient: PointwiseRatio = field()", # markdown-exec: hide - " induced_drag_factor: PointwiseRatio = field()", # markdown-exec: hide - " propulsive_efficiency: PointwiseRatio = field()", # markdown-exec: hide - " nox_emission_index: PointwiseRatio = field()", # markdown-exec: hide - " soot_emission_index: PointwiseRatio = field()", # markdown-exec: hide + " altitude: Length = field()", # markdown-exec: hide + " mach: Ratio = field()", # markdown-exec: hide + " mass: Mass = field()", # markdown-exec: hide + " temperature_offset: TemperatureChange = field()", # markdown-exec: hide + " wing_area: Area = field()", # markdown-exec: hide + " zero_lift_drag_coefficient: Ratio = field()", # markdown-exec: hide + " induced_drag_factor: Ratio = field()", # markdown-exec: hide + " propulsive_efficiency: Ratio = field()", # markdown-exec: hide + " nox_emission_index: Ratio = field()", # markdown-exec: hide + " soot_emission_index: Ratio = field()", # markdown-exec: hide "", # markdown-exec: hide " # Atmosphere", # markdown-exec: hide - " temperature: PointwiseAbsoluteTemperature = field()", # markdown-exec: hide - " pressure: PointwisePressure = field()", # markdown-exec: hide - " density: PointwiseDensity = field()", # markdown-exec: hide - " speed_of_sound: PointwiseSpeed = field()", # markdown-exec: hide - " true_airspeed: PointwiseSpeed = field()", # markdown-exec: hide + " temperature: AbsoluteTemperature = field()", # markdown-exec: hide + " pressure: Pressure = field()", # markdown-exec: hide + " density: Density = field()", # markdown-exec: hide + " speed_of_sound: Speed = field()", # markdown-exec: hide + " true_airspeed: Speed = field()", # markdown-exec: hide "", # markdown-exec: hide " # Aerodynamics", # markdown-exec: hide - " weight: PointwiseForce = field()", # markdown-exec: hide - " dynamic_pressure: PointwisePressure = field()", # markdown-exec: hide - " lift_coefficient: PointwiseRatio = field()", # markdown-exec: hide - " parasite_drag: PointwiseForce = field()", # markdown-exec: hide - " induced_drag: PointwiseForce = field()", # markdown-exec: hide - " compressibility_drag: PointwiseForce = field()", # markdown-exec: hide - " trim_drag: PointwiseForce = field()", # markdown-exec: hide - " total_drag: PointwiseForce = field()", # markdown-exec: hide + " weight: Force = field()", # markdown-exec: hide + " dynamic_pressure: Pressure = field()", # markdown-exec: hide + " lift_coefficient: Ratio = field()", # markdown-exec: hide + " parasite_drag: Force = field()", # markdown-exec: hide + " induced_drag: Force = field()", # markdown-exec: hide + " compressibility_drag: Force = field()", # markdown-exec: hide + " trim_drag: Force = field()", # markdown-exec: hide + " total_drag: Force = field()", # markdown-exec: hide "", # markdown-exec: hide " # Propulsion", # markdown-exec: hide - " propulsive_power: PointwisePower = field()", # markdown-exec: hide - " fuel_power: PointwisePower = field()", # markdown-exec: hide - " fuel_flow: PointwiseMassRate = field()", # markdown-exec: hide + " propulsive_power: Power = field()", # markdown-exec: hide + " fuel_power: Power = field()", # markdown-exec: hide + " fuel_flow: MassRate = field()", # markdown-exec: hide "", # markdown-exec: hide " # Emissions", # markdown-exec: hide - " co2_rate: PointwiseMassRate = field()", # markdown-exec: hide - " water_rate: PointwiseMassRate = field()", # markdown-exec: hide - " nox_rate: PointwiseMassRate = field()", # markdown-exec: hide - " soot_rate: PointwiseMassRate = field()", # markdown-exec: hide + " co2_rate: MassRate = field()", # markdown-exec: hide + " water_rate: MassRate = field()", # markdown-exec: hide + " nox_rate: MassRate = field()", # markdown-exec: hide + " soot_rate: MassRate = field()", # markdown-exec: hide "", # markdown-exec: hide " # Illustrative climate-effect outputs", # markdown-exec: hide - " co2_effect: PointwiseMassRate = field()", # markdown-exec: hide - " water_effect: PointwiseMassRate = field()", # markdown-exec: hide - " nox_effect: PointwiseMassRate = field()", # markdown-exec: hide - " soot_effect: PointwiseMassRate = field()", # markdown-exec: hide - " contrail_effect: PointwiseMassRate = field()", # markdown-exec: hide - " total_climate_effect: PointwiseMassRate = field()", # markdown-exec: hide + " co2_effect: MassRate = field()", # markdown-exec: hide + " water_effect: MassRate = field()", # markdown-exec: hide + " nox_effect: MassRate = field()", # markdown-exec: hide + " soot_effect: MassRate = field()", # markdown-exec: hide + " contrail_effect: MassRate = field()", # markdown-exec: hide + " total_climate_effect: MassRate = field()", # markdown-exec: hide "", # markdown-exec: hide "", # markdown-exec: hide "# Atmosphere -----------------------------------------------------------------", # markdown-exec: hide @@ -223,7 +210,7 @@ _model_source = ( # markdown-exec: hide "", # markdown-exec: hide "@transform", # markdown-exec: hide "def temperature(altitude: Length, temperature_offset: TemperatureChange) -> AbsoluteTemperature:", # markdown-exec: hide - " return Quantity(288.15, absolute_kelvin) - (0.0065 * kelvin / meter) * altitude + temperature_offset", # markdown-exec: hide + " return 288.15 * absolute_kelvin - (0.0065 * kelvin / meter) * altitude + temperature_offset", # markdown-exec: hide "", # markdown-exec: hide "", # markdown-exec: hide "@transform", # markdown-exec: hide @@ -385,7 +372,7 @@ _model_source = ( # markdown-exec: hide "", # markdown-exec: hide "@transform", # markdown-exec: hide "def water_effect(water_rate: MassRate, altitude: Length) -> MassRate:", # markdown-exec: hide - " altitude_factor = Quantity(0.8, UNITLESS) + altitude / (50_000.0 * meter)", # markdown-exec: hide + " altitude_factor = 0.8 * UNITLESS + altitude / (50_000.0 * meter)", # markdown-exec: hide " return 0.15 * water_rate * altitude_factor", # markdown-exec: hide "", # markdown-exec: hide "", # markdown-exec: hide @@ -395,14 +382,14 @@ _model_source = ( # markdown-exec: hide " altitude: Length,", # markdown-exec: hide " temperature: AbsoluteTemperature,", # markdown-exec: hide ") -> MassRate:", # markdown-exec: hide - " altitude_factor = Quantity(0.5, UNITLESS) + altitude / (20_000.0 * meter)", # markdown-exec: hide + " altitude_factor = 0.5 * UNITLESS + altitude / (20_000.0 * meter)", # markdown-exec: hide " temperature_factor = 288.15 / temperature.convert_to(absolute_kelvin).value", # markdown-exec: hide " return 40.0 * nox_rate * altitude_factor * temperature_factor", # markdown-exec: hide "", # markdown-exec: hide "", # markdown-exec: hide "@transform", # markdown-exec: hide "def soot_effect(soot_rate: MassRate, altitude: Length) -> MassRate:", # markdown-exec: hide - " altitude_factor = Quantity(0.5, UNITLESS) + altitude / (15_000.0 * meter)", # markdown-exec: hide + " altitude_factor = 0.5 * UNITLESS + altitude / (15_000.0 * meter)", # markdown-exec: hide " return 1000.0 * soot_rate * altitude_factor", # markdown-exec: hide "", # markdown-exec: hide "", # markdown-exec: hide @@ -418,7 +405,7 @@ _model_source = ( # markdown-exec: hide " return (", # markdown-exec: hide " 0.08", # markdown-exec: hide " * water_rate", # markdown-exec: hide - " * (Quantity(1.0, UNITLESS) + (100.0 * second / kilogram) * soot_rate)", # markdown-exec: hide + " * (1.0 * UNITLESS + (100.0 * second / kilogram) * soot_rate)", # markdown-exec: hide " * altitude_factor", # markdown-exec: hide " * temperature_factor", # markdown-exec: hide " )", # markdown-exec: hide @@ -570,12 +557,12 @@ inputs = { over=scenario, unit=kelvin, ), - "wing_area": Quantity(float(np.float32(122.6)), meter**2), - "zero_lift_drag_coefficient": Quantity(float(np.float32(0.021)), UNITLESS), - "induced_drag_factor": Quantity(float(np.float32(0.045)), UNITLESS), - "propulsive_efficiency": Quantity(float(np.float32(0.38)), UNITLESS), - "nox_emission_index": Quantity(float(np.float32(0.015)), UNITLESS), - "soot_emission_index": Quantity(float(np.float32(0.00003)), UNITLESS), + "wing_area": float(np.float32(122.6)) * (meter**2), + "zero_lift_drag_coefficient": float(np.float32(0.021)) * UNITLESS, + "induced_drag_factor": float(np.float32(0.045)) * UNITLESS, + "propulsive_efficiency": float(np.float32(0.38)) * UNITLESS, + "nox_emission_index": float(np.float32(0.015)) * UNITLESS, + "soot_emission_index": float(np.float32(0.00003)) * UNITLESS, } print(f"Scenarios: **{scenario_count:,}**") @@ -743,12 +730,12 @@ for exponent in (12, 14, 16, 18): over=scenario, unit=kelvin, ), - "wing_area": Quantity(float(np.float32(122.6)), meter**2), - "zero_lift_drag_coefficient": Quantity(float(np.float32(0.021)), UNITLESS), - "induced_drag_factor": Quantity(float(np.float32(0.045)), UNITLESS), - "propulsive_efficiency": Quantity(float(np.float32(0.38)), UNITLESS), - "nox_emission_index": Quantity(float(np.float32(0.015)), UNITLESS), - "soot_emission_index": Quantity(float(np.float32(0.00003)), UNITLESS), + "wing_area": float(np.float32(122.6)) * (meter**2), + "zero_lift_drag_coefficient": float(np.float32(0.021)) * UNITLESS, + "induced_drag_factor": float(np.float32(0.045)) * UNITLESS, + "propulsive_efficiency": float(np.float32(0.38)) * UNITLESS, + "nox_emission_index": float(np.float32(0.015)) * UNITLESS, + "soot_emission_index": float(np.float32(0.00003)) * UNITLESS, } python_times = [] diff --git a/docs/worked_examples/two-shaft-gas-turbine.md b/docs/worked_examples/two-shaft-gas-turbine.md index 9aa997cb..603ecab3 100644 --- a/docs/worked_examples/two-shaft-gas-turbine.md +++ b/docs/worked_examples/two-shaft-gas-turbine.md @@ -80,7 +80,7 @@ To determine how much work the LP turbine extracts, we therefore specify the **c For the baseline example we use: ```text -core exit temperature = Quantity(1000, absolute_kelvin) K +core exit temperature = 1000 K ``` A real engine model would usually determine the turbine expansion from pressures and component efficiencies. Here the fixed exit temperature keeps the physics intentionally low-order while giving the shaft-power calculation a well-defined endpoint. @@ -120,9 +120,9 @@ def render_plot() -> None: ## 1. Define reusable component systems -We start with a compressor. Its system fields use named pointwise quantity -aliases, allowing scalar or tensor values without fixing array shapes. -The equations retain scalar aliases, which Bilt can lift over tensor domains. +We start with a compressor. Its system fields and equations share one quantity +alias per dimension; each accepts a single value or a tensor of values without +fixing array shapes, and Bilt lifts the equations over tensor domains. Temperatures are absolute readings; subtracting two readings gives a relative temperature change. Specific heat multiplies that change to produce specific @@ -135,7 +135,7 @@ than encoded in names such as `_k` or `_kj_per_kg`. ```python exec="off" from typing import Annotated -from bilt import Implementation, Interface, Quantity, QuantityTensor, equation, field, system +from bilt import Implementation, Interface, Quantity, equation, field, system from bilt.units import UNITLESS, absolute_kelvin, kelvin, kilogram, kilojoule, kilowatt, megawatt, second from bilt.units.dimensions import ABSOLUTE, DIMENSIONLESS, ENERGY, MASS, TEMPERATURE, TIME @@ -147,23 +147,16 @@ MassFlow = Annotated[Quantity, MASS / TIME] Power = Annotated[Quantity, ENERGY / TIME] Ratio = Annotated[Quantity, DIMENSIONLESS] -PointwiseAbsoluteTemperature = Annotated[Quantity | QuantityTensor, TEMPERATURE, ABSOLUTE] -PointwiseSpecificHeat = Annotated[Quantity | QuantityTensor, ENERGY / (MASS * TEMPERATURE)] -PointwiseSpecificWork = Annotated[Quantity | QuantityTensor, ENERGY / MASS] -PointwiseMassFlow = Annotated[Quantity | QuantityTensor, MASS / TIME] -PointwisePower = Annotated[Quantity | QuantityTensor, ENERGY / TIME] -PointwiseRatio = Annotated[Quantity | QuantityTensor, DIMENSIONLESS] - @system class Compressor(metaclass=Interface): - inlet_temperature: PointwiseAbsoluteTemperature = field() - outlet_temperature: PointwiseAbsoluteTemperature = field() - pressure_ratio: PointwiseRatio = field() - isentropic_efficiency: PointwiseRatio = field() - gamma: PointwiseRatio = field() - specific_heat: PointwiseSpecificHeat = field() - specific_work: PointwiseSpecificWork = field() + inlet_temperature: AbsoluteTemperature = field() + outlet_temperature: AbsoluteTemperature = field() + pressure_ratio: Ratio = field() + isentropic_efficiency: Ratio = field() + gamma: Ratio = field() + specific_heat: SpecificHeat = field() + specific_work: SpecificWork = field() @equation @@ -175,7 +168,7 @@ def compressor_temperature_relation( gamma: Ratio, ) -> bool: return (outlet_temperature - inlet_temperature) * isentropic_efficiency == ( - inlet_temperature - Quantity(0.0, absolute_kelvin) + inlet_temperature - 0.0 * absolute_kelvin ) * (pressure_ratio ** ((gamma - 1.0) / gamma) - 1.0) @@ -199,7 +192,7 @@ compressor_model = Implementation( ``` The compressor temperature relation uses -`inlet_temperature - Quantity(0.0, absolute_kelvin)` to express the inlet +`inlet_temperature - 0.0 * absolute_kelvin` to express the inlet temperature relative to absolute zero before multiplying it by a dimensionless factor. This preserves the original kelvin-based formula while distinguishing absolute readings from relative changes. @@ -217,15 +210,12 @@ does not permanently designate specific work as the output. With a different set The turbine is similarly small: ```python exec="off" -from bilt import QuantityTensor - - @system class Turbine(metaclass=Interface): - inlet_temperature: PointwiseAbsoluteTemperature = field() - outlet_temperature: PointwiseAbsoluteTemperature = field() - specific_heat: PointwiseSpecificHeat = field() - specific_work: PointwiseSpecificWork = field() + inlet_temperature: AbsoluteTemperature = field() + outlet_temperature: AbsoluteTemperature = field() + specific_heat: SpecificHeat = field() + specific_work: SpecificWork = field() @equation @@ -249,43 +239,40 @@ turbine_model = Implementation( The parent system contains the values needed to connect the four child systems. ```python exec="off" -from bilt import QuantityTensor - - @system class TwoShaftCore(metaclass=Interface): # Gas-path temperatures. - inlet_temperature: PointwiseAbsoluteTemperature = field() - low_pressure_compressor_exit_temperature: PointwiseAbsoluteTemperature = field() - high_pressure_compressor_exit_temperature: PointwiseAbsoluteTemperature = field() - turbine_inlet_temperature: PointwiseAbsoluteTemperature = field() - high_pressure_turbine_exit_temperature: PointwiseAbsoluteTemperature = field() - exit_temperature: PointwiseAbsoluteTemperature = field() + inlet_temperature: AbsoluteTemperature = field() + low_pressure_compressor_exit_temperature: AbsoluteTemperature = field() + high_pressure_compressor_exit_temperature: AbsoluteTemperature = field() + turbine_inlet_temperature: AbsoluteTemperature = field() + high_pressure_turbine_exit_temperature: AbsoluteTemperature = field() + exit_temperature: AbsoluteTemperature = field() # Compressor design assumptions. - low_pressure_compressor_pressure_ratio: PointwiseRatio = field() - high_pressure_compressor_pressure_ratio: PointwiseRatio = field() - low_pressure_compressor_efficiency: PointwiseRatio = field() - high_pressure_compressor_efficiency: PointwiseRatio = field() + low_pressure_compressor_pressure_ratio: Ratio = field() + high_pressure_compressor_pressure_ratio: Ratio = field() + low_pressure_compressor_efficiency: Ratio = field() + high_pressure_compressor_efficiency: Ratio = field() # Shared fluid properties. - gamma: PointwiseRatio = field() - specific_heat: PointwiseSpecificHeat = field() + gamma: Ratio = field() + specific_heat: SpecificHeat = field() # Shaft efficiencies. - low_pressure_shaft_efficiency: PointwiseRatio = field() - high_pressure_shaft_efficiency: PointwiseRatio = field() + low_pressure_shaft_efficiency: Ratio = field() + high_pressure_shaft_efficiency: Ratio = field() # Coupling values used by the two shaft balances. - low_pressure_compressor_work: PointwiseSpecificWork = field() - high_pressure_compressor_work: PointwiseSpecificWork = field() - high_pressure_turbine_work: PointwiseSpecificWork = field() - low_pressure_turbine_work: PointwiseSpecificWork = field() + low_pressure_compressor_work: SpecificWork = field() + high_pressure_compressor_work: SpecificWork = field() + high_pressure_turbine_work: SpecificWork = field() + low_pressure_turbine_work: SpecificWork = field() # Useful LP-shaft output. - shaft_output_work: PointwiseSpecificWork = field() - mass_flow: PointwiseMassFlow = field() - shaft_power: PointwisePower = field() + shaft_output_work: SpecificWork = field() + mass_flow: MassFlow = field() + shaft_power: Power = field() ``` Some of these values exist mainly to provide an explicit hand-off between child systems. @@ -664,7 +651,7 @@ For the executable documentation below, the same model is loaded from a temporar model_source = """ from typing import Annotated -from bilt import Implementation, Interface, Quantity, QuantityTensor, equation, field, system +from bilt import Implementation, Interface, Quantity, equation, field, system from bilt.units import UNITLESS, absolute_kelvin, kelvin, kilogram, kilojoule, kilowatt, megawatt, second from bilt.units.dimensions import ABSOLUTE, DIMENSIONLESS, ENERGY, MASS, TEMPERATURE, TIME @@ -676,22 +663,16 @@ MassFlow = Annotated[Quantity, MASS / TIME] Power = Annotated[Quantity, ENERGY / TIME] Ratio = Annotated[Quantity, DIMENSIONLESS] -PointwiseAbsoluteTemperature = Annotated[Quantity | QuantityTensor, TEMPERATURE, ABSOLUTE] -PointwiseSpecificHeat = Annotated[Quantity | QuantityTensor, ENERGY / (MASS * TEMPERATURE)] -PointwiseSpecificWork = Annotated[Quantity | QuantityTensor, ENERGY / MASS] -PointwiseMassFlow = Annotated[Quantity | QuantityTensor, MASS / TIME] -PointwisePower = Annotated[Quantity | QuantityTensor, ENERGY / TIME] -PointwiseRatio = Annotated[Quantity | QuantityTensor, DIMENSIONLESS] @system class Compressor(metaclass=Interface): - inlet_temperature: PointwiseAbsoluteTemperature = field() - outlet_temperature: PointwiseAbsoluteTemperature = field() - pressure_ratio: PointwiseRatio = field() - isentropic_efficiency: PointwiseRatio = field() - gamma: PointwiseRatio = field() - specific_heat: PointwiseSpecificHeat = field() - specific_work: PointwiseSpecificWork = field() + inlet_temperature: AbsoluteTemperature = field() + outlet_temperature: AbsoluteTemperature = field() + pressure_ratio: Ratio = field() + isentropic_efficiency: Ratio = field() + gamma: Ratio = field() + specific_heat: SpecificHeat = field() + specific_work: SpecificWork = field() @equation def compressor_temperature_relation( @@ -704,7 +685,7 @@ def compressor_temperature_relation( return ( (outlet_temperature - inlet_temperature) * isentropic_efficiency - == (inlet_temperature - Quantity(0.0, absolute_kelvin)) + == (inlet_temperature - 0.0 * absolute_kelvin) * ( pressure_ratio ** ((gamma - 1.0) / gamma) - 1.0 @@ -734,10 +715,10 @@ compressor_model = Implementation( @system class Turbine(metaclass=Interface): - inlet_temperature: PointwiseAbsoluteTemperature = field() - outlet_temperature: PointwiseAbsoluteTemperature = field() - specific_heat: PointwiseSpecificHeat = field() - specific_work: PointwiseSpecificWork = field() + inlet_temperature: AbsoluteTemperature = field() + outlet_temperature: AbsoluteTemperature = field() + specific_heat: SpecificHeat = field() + specific_work: SpecificWork = field() @equation def turbine_work_relation( @@ -759,33 +740,33 @@ turbine_model = Implementation( @system class TwoShaftCore(metaclass=Interface): - inlet_temperature: PointwiseAbsoluteTemperature = field() - low_pressure_compressor_exit_temperature: PointwiseAbsoluteTemperature = field() - high_pressure_compressor_exit_temperature: PointwiseAbsoluteTemperature = field() - turbine_inlet_temperature: PointwiseAbsoluteTemperature = field() - high_pressure_turbine_exit_temperature: PointwiseAbsoluteTemperature = field() - exit_temperature: PointwiseAbsoluteTemperature = field() + inlet_temperature: AbsoluteTemperature = field() + low_pressure_compressor_exit_temperature: AbsoluteTemperature = field() + high_pressure_compressor_exit_temperature: AbsoluteTemperature = field() + turbine_inlet_temperature: AbsoluteTemperature = field() + high_pressure_turbine_exit_temperature: AbsoluteTemperature = field() + exit_temperature: AbsoluteTemperature = field() - low_pressure_compressor_pressure_ratio: PointwiseRatio = field() - high_pressure_compressor_pressure_ratio: PointwiseRatio = field() - low_pressure_compressor_efficiency: PointwiseRatio = field() - high_pressure_compressor_efficiency: PointwiseRatio = field() + low_pressure_compressor_pressure_ratio: Ratio = field() + high_pressure_compressor_pressure_ratio: Ratio = field() + low_pressure_compressor_efficiency: Ratio = field() + high_pressure_compressor_efficiency: Ratio = field() - gamma: PointwiseRatio = field() - specific_heat: PointwiseSpecificHeat = field() + gamma: Ratio = field() + specific_heat: SpecificHeat = field() - low_pressure_shaft_efficiency: PointwiseRatio = field() - high_pressure_shaft_efficiency: PointwiseRatio = field() + low_pressure_shaft_efficiency: Ratio = field() + high_pressure_shaft_efficiency: Ratio = field() - low_pressure_compressor_work: PointwiseSpecificWork = field() - high_pressure_compressor_work: PointwiseSpecificWork = field() - high_pressure_turbine_work: PointwiseSpecificWork = field() - low_pressure_turbine_work: PointwiseSpecificWork = field() + low_pressure_compressor_work: SpecificWork = field() + high_pressure_compressor_work: SpecificWork = field() + high_pressure_turbine_work: SpecificWork = field() + low_pressure_turbine_work: SpecificWork = field() # Useful LP-shaft output. - shaft_output_work: PointwiseSpecificWork = field() - mass_flow: PointwiseMassFlow = field() - shaft_power: PointwisePower = field() + shaft_output_work: SpecificWork = field() + mass_flow: MassFlow = field() + shaft_power: Power = field() @equation def low_pressure_compressor_inlet_connection( @@ -1100,16 +1081,16 @@ explicitly convert to kJ/kg and MW for the printed results and plots. ```python exec="on" source="above" session="turbomachinery" baseline = TwoShaftCore( - inlet_temperature=Quantity(288.0, absolute_kelvin), - low_pressure_compressor_pressure_ratio=Quantity(2.0, UNITLESS), - high_pressure_compressor_pressure_ratio=Quantity(6.0, UNITLESS), - low_pressure_compressor_efficiency=Quantity(0.88, UNITLESS), - high_pressure_compressor_efficiency=Quantity(0.86, UNITLESS), - turbine_inlet_temperature=Quantity(1450.0, absolute_kelvin), - exit_temperature=Quantity(1000.0, absolute_kelvin), - low_pressure_shaft_efficiency=Quantity(0.99, UNITLESS), - high_pressure_shaft_efficiency=Quantity(0.99, UNITLESS), - gamma=Quantity(1.4, UNITLESS), + inlet_temperature=288.0 * absolute_kelvin, + low_pressure_compressor_pressure_ratio=2.0 * UNITLESS, + high_pressure_compressor_pressure_ratio=6.0 * UNITLESS, + low_pressure_compressor_efficiency=0.88 * UNITLESS, + high_pressure_compressor_efficiency=0.86 * UNITLESS, + turbine_inlet_temperature=1450.0 * absolute_kelvin, + exit_temperature=1000.0 * absolute_kelvin, + low_pressure_shaft_efficiency=0.99 * UNITLESS, + high_pressure_shaft_efficiency=0.99 * UNITLESS, + gamma=1.4 * UNITLESS, specific_heat=1.005 * kilojoule / (kilogram * kelvin), mass_flow=20.0 * kilogram / second, ) @@ -1299,16 +1280,16 @@ The inverse operating point is: ```python exec="on" source="above" session="turbomachinery" inverse_case = TwoShaftCore( - inlet_temperature=Quantity(288.0, absolute_kelvin), - low_pressure_compressor_pressure_ratio=Quantity(2.0, UNITLESS), - high_pressure_compressor_pressure_ratio=Quantity(6.0, UNITLESS), - low_pressure_compressor_efficiency=Quantity(0.88, UNITLESS), + inlet_temperature=288.0 * absolute_kelvin, + low_pressure_compressor_pressure_ratio=2.0 * UNITLESS, + high_pressure_compressor_pressure_ratio=6.0 * UNITLESS, + low_pressure_compressor_efficiency=0.88 * UNITLESS, # high_pressure_compressor_efficiency is deliberately omitted - turbine_inlet_temperature=Quantity(1450.0, absolute_kelvin), - exit_temperature=Quantity(1000.0, absolute_kelvin), - low_pressure_shaft_efficiency=Quantity(0.99, UNITLESS), - high_pressure_shaft_efficiency=Quantity(0.99, UNITLESS), - gamma=Quantity(1.4, UNITLESS), + turbine_inlet_temperature=1450.0 * absolute_kelvin, + exit_temperature=1000.0 * absolute_kelvin, + low_pressure_shaft_efficiency=0.99 * UNITLESS, + high_pressure_shaft_efficiency=0.99 * UNITLESS, + gamma=1.4 * UNITLESS, specific_heat=1.005 * kilojoule / (kilogram * kelvin), mass_flow=20.0 * kilogram / second, shaft_power=2000.0 * kilowatt, @@ -1404,18 +1385,18 @@ required_high_pressure_compressor_efficiencies = [] for required_power_mw in required_powers_mw: core = TwoShaftCore( - inlet_temperature=Quantity(288.0, absolute_kelvin), - low_pressure_compressor_pressure_ratio=Quantity(2.0, UNITLESS), - high_pressure_compressor_pressure_ratio=Quantity(6.0, UNITLESS), - low_pressure_compressor_efficiency=Quantity(0.88, UNITLESS), - turbine_inlet_temperature=Quantity(1450.0, absolute_kelvin), - exit_temperature=Quantity(1000.0, absolute_kelvin), - low_pressure_shaft_efficiency=Quantity(0.99, UNITLESS), - high_pressure_shaft_efficiency=Quantity(0.99, UNITLESS), - gamma=Quantity(1.4, UNITLESS), + inlet_temperature=288.0 * absolute_kelvin, + low_pressure_compressor_pressure_ratio=2.0 * UNITLESS, + high_pressure_compressor_pressure_ratio=6.0 * UNITLESS, + low_pressure_compressor_efficiency=0.88 * UNITLESS, + turbine_inlet_temperature=1450.0 * absolute_kelvin, + exit_temperature=1000.0 * absolute_kelvin, + low_pressure_shaft_efficiency=0.99 * UNITLESS, + high_pressure_shaft_efficiency=0.99 * UNITLESS, + gamma=1.4 * UNITLESS, specific_heat=1.005 * kilojoule / (kilogram * kelvin), mass_flow=20.0 * kilogram / second, - shaft_power=Quantity(float(required_power_mw), megawatt), + shaft_power=float(required_power_mw) * megawatt, ) with core_model: @@ -1477,13 +1458,13 @@ mass_flow = 25.0 * kilogram / second or change the maximum turbine inlet temperature: ```python exec="off" -turbine_inlet_temperature = Quantity(1500.0, absolute_kelvin) +turbine_inlet_temperature = 1500.0 * absolute_kelvin ``` You can also change the compressor pressure-ratio target: ```python exec="off" -high_pressure_compressor_pressure_ratio = Quantity(7.0, UNITLESS) +high_pressure_compressor_pressure_ratio = 7.0 * UNITLESS ``` and ask again what compressor efficiency is required for a specified shaft power. @@ -1491,7 +1472,7 @@ and ask again what compressor efficiency is required for a specified shaft power Another useful experiment is to change the core exit boundary: ```python exec="off" -exit_temperature = Quantity(950.0, absolute_kelvin) +exit_temperature = 950.0 * absolute_kelvin ``` To explore locally, edit these values while `zensical serve` is running and save the Markdown file. Zensical will rebuild the page and rerun the executable blocks. @@ -1776,18 +1757,18 @@ recuperated_model = Implementation( ) inputs = { - "core.inlet_temperature": Quantity(288, absolute_kelvin), - "core.low_pressure_compressor_pressure_ratio": Quantity(2, UNITLESS), - "core.high_pressure_compressor_pressure_ratio": Quantity(6, UNITLESS), - "core.low_pressure_compressor_efficiency": Quantity(0.88, UNITLESS), - "core.high_pressure_compressor_efficiency": Quantity(0.86, UNITLESS), - "core.low_pressure_shaft_efficiency": Quantity(0.99, UNITLESS), - "core.high_pressure_shaft_efficiency": Quantity(0.99, UNITLESS), - "core.gamma": Quantity(1.4, UNITLESS), + "core.inlet_temperature": 288 * absolute_kelvin, + "core.low_pressure_compressor_pressure_ratio": 2 * UNITLESS, + "core.high_pressure_compressor_pressure_ratio": 6 * UNITLESS, + "core.low_pressure_compressor_efficiency": 0.88 * UNITLESS, + "core.high_pressure_compressor_efficiency": 0.86 * UNITLESS, + "core.low_pressure_shaft_efficiency": 0.99 * UNITLESS, + "core.high_pressure_shaft_efficiency": 0.99 * UNITLESS, + "core.gamma": 1.4 * UNITLESS, "core.specific_heat": 1.005 * kilojoule / (kilogram * kelvin), "core.mass_flow": 20.0 * kilogram / second, "heat_input": 600.0 * kilojoule / kilogram, - "effectiveness": Quantity(0.6, UNITLESS), + "effectiveness": 0.6 * UNITLESS, "shaft_power": 2.0 * megawatt, } diff --git a/docs/worked_examples/two-springs-in-series.md b/docs/worked_examples/two-springs-in-series.md index 49053351..2bc4f8c1 100644 --- a/docs/worked_examples/two-springs-in-series.md +++ b/docs/worked_examples/two-springs-in-series.md @@ -82,14 +82,14 @@ A spring has three boundary values: stiffness, extension, and force. We declare their dimensions rather than fixing particular units. Stiffness has dimension force per length, extension has dimension length, and force has dimension force. -The system fields use pointwise aliases to accept scalar quantities or -unit-carrying tensors. The equations retain scalar aliases that Bilt can lift -over named domains. Here we supply stiffness in N/m, extension in m, and force in N: +Each alias accepts a single quantity or a tensor of quantities, so the system +fields and the equations share them; Bilt lifts the equations over named +domains. Here we supply stiffness in N/m, extension in m, and force in N: ```python exec="off" from typing import Annotated -from bilt import Implementation, Interface, Quantity, QuantityTensor, equation, field, system +from bilt import Implementation, Interface, Quantity, equation, field, system from bilt.units import meter, newton from bilt.units.dimensions import FORCE, LENGTH @@ -98,16 +98,12 @@ Stiffness = Annotated[Quantity, FORCE / LENGTH] Length = Annotated[Quantity, LENGTH] Force = Annotated[Quantity, FORCE] -PointwiseStiffness = Annotated[Quantity | QuantityTensor, FORCE / LENGTH] -PointwiseLength = Annotated[Quantity | QuantityTensor, LENGTH] -PointwiseForce = Annotated[Quantity | QuantityTensor, FORCE] - @system class Spring(metaclass=Interface): - stiffness: PointwiseStiffness = field() - extension: PointwiseLength = field() - force: PointwiseForce = field() + stiffness: Stiffness = field() + extension: Length = field() + force: Force = field() ``` Hooke's law is an equation: @@ -149,19 +145,16 @@ That is the acausal part of the component model. The parent system exposes the values we want to use when working with two springs: ```python exec="off" -from bilt import QuantityTensor - - @system class DoubleSpring(metaclass=Interface): - first_stiffness: PointwiseStiffness = field() - second_stiffness: PointwiseStiffness = field() + first_stiffness: Stiffness = field() + second_stiffness: Stiffness = field() - first_extension: PointwiseLength = field() - second_extension: PointwiseLength = field() - total_extension: PointwiseLength = field() + first_extension: Length = field() + second_extension: Length = field() + total_extension: Length = field() - force: PointwiseForce = field() + force: Force = field() ``` The two `Spring` occurrences are not public fields. They belong to this implementation of `DoubleSpring`. @@ -321,7 +314,7 @@ For the executable documentation below, the same model is loaded from a temporar model_source = """ from typing import Annotated -from bilt import Implementation, Interface, Quantity, QuantityTensor, equation, field, system +from bilt import Implementation, Interface, Quantity, equation, field, system from bilt.units import meter, newton from bilt.units.dimensions import FORCE, LENGTH @@ -330,15 +323,12 @@ Stiffness = Annotated[Quantity, FORCE / LENGTH] Length = Annotated[Quantity, LENGTH] Force = Annotated[Quantity, FORCE] -PointwiseStiffness = Annotated[Quantity | QuantityTensor, FORCE / LENGTH] -PointwiseLength = Annotated[Quantity | QuantityTensor, LENGTH] -PointwiseForce = Annotated[Quantity | QuantityTensor, FORCE] @system class Spring(metaclass=Interface): - stiffness: PointwiseStiffness = field() - extension: PointwiseLength = field() - force: PointwiseForce = field() + stiffness: Stiffness = field() + extension: Length = field() + force: Force = field() @equation def hookes_law( @@ -355,14 +345,14 @@ linear_spring = Implementation( @system class DoubleSpring(metaclass=Interface): - first_stiffness: PointwiseStiffness = field() - second_stiffness: PointwiseStiffness = field() + first_stiffness: Stiffness = field() + second_stiffness: Stiffness = field() - first_extension: PointwiseLength = field() - second_extension: PointwiseLength = field() - total_extension: PointwiseLength = field() + first_extension: Length = field() + second_extension: Length = field() + total_extension: Length = field() - force: PointwiseForce = field() + force: Force = field() @equation def first_stiffness_connection( diff --git a/src/bilt/__init__.py b/src/bilt/__init__.py index 79307efe..a29d0b65 100644 --- a/src/bilt/__init__.py +++ b/src/bilt/__init__.py @@ -7,7 +7,8 @@ from bilt.core._equation import equation from bilt.core._interface import Interface from bilt.core._system import Implementation, field, system -from bilt.core._tensors._tensors import QuantityTensor, Tensor, tensor +from bilt.core._tensors._protocols import Number, QuantityTensor, Tensor +from bilt.core._tensors._tensors import tensor from bilt.core._transform import transform from bilt.symbolic._dimensions import CoordinateAxis, Dim, coordinate_axis, dim from bilt.symbolic._domains import Domain, as_domain, domain @@ -24,6 +25,7 @@ "Domain", "Implementation", "Interface", + "Number", "Quantity", "QuantityTensor", "Tensor", diff --git a/src/bilt/core/_equation.py b/src/bilt/core/_equation.py index 1469086f..54724832 100644 --- a/src/bilt/core/_equation.py +++ b/src/bilt/core/_equation.py @@ -21,7 +21,7 @@ from bilt.core._port import QualifiedPort from bilt.core._port_declaration import PortDeclaration, annotated_parts, port_declarations, quantity_magnitude_kind from bilt.core._sub_system import validate_name -from bilt.core._tensors._tensors import QuantityTensor, Tensor +from bilt.core._tensors._protocols import QuantityTensor, Tensor from bilt.core._validation import validate_independently from bilt.symbolic import _atoms as ops from bilt.symbolic._atoms import QuantityType, SymbolType diff --git a/src/bilt/core/_port_declaration.py b/src/bilt/core/_port_declaration.py index 5510a587..3966e2c9 100644 --- a/src/bilt/core/_port_declaration.py +++ b/src/bilt/core/_port_declaration.py @@ -7,7 +7,7 @@ import typing from bilt.core._errors import BiltPortDeclarationError -from bilt.core._tensors._tensors import QuantityTensor, Tensor +from bilt.core._tensors._protocols import QuantityTensor, Tensor from bilt.core._validation import validate_independently from bilt.symbolic._domains import Domain from bilt.units import Dimension, Metadata, Quantity, Unit @@ -23,15 +23,15 @@ class PortDeclaration: """What a declared port holds: a quantity of its dimensionality, absolute if marked and relative otherwise. - `over_a_domain` records that the port requires a tensor quantity. It says what a caller may - pass at this port, not what the port measures, so it takes no part in a declaration's identity: a constituent - written over scalars is reusable in a tensor system under the same port name. + `over_a_domain` records that the port requires a tensor quantity (`QuantityTensor`); otherwise it takes a + quantity of any shape (`Quantity`). It says what a caller may pass at this port, not what the port measures, so + it takes no part in a declaration's identity: a constituent written over scalars is reusable in a tensor system + under the same port name. """ dimensionality: Dimension absolute: bool = False over_a_domain: bool = dataclasses.field(default=False, compare=False) - scalar_only: bool = dataclasses.field(default=False, compare=False) required_domain: Domain | None = dataclasses.field(default=None, compare=False) @property @@ -54,8 +54,8 @@ def annotated_parts(annotation: object) -> tuple[object, list[object]]: return annotation, [] -def _is_pointwise_quantity_union(base_type: object) -> bool: - """Check the exact scalar-or-tensor quantity union, not arbitrary unions.""" +def _is_old_pointwise_quantity_union(base_type: object) -> bool: + """Whether this is `Quantity | QuantityTensor`, which means the same as `Quantity`.""" return typing.get_origin(base_type) in (typing.Union, types.UnionType) and frozenset( typing.get_args(base_type) ) == { @@ -64,17 +64,37 @@ def _is_pointwise_quantity_union(base_type: object) -> bool: } -def quantity_magnitude_kind(base_type: object) -> typing.Literal["scalar", "tensor", "either"] | None: - """Classify a quantity annotation by the shape it accepts.""" - if _is_pointwise_quantity_union(base_type): - return "either" - if base_type is Quantity: - return "scalar" +def quantity_magnitude_kind(base_type: object) -> typing.Literal["tensor", "any"] | None: + """Classify a quantity annotation by the shape it accepts: `QuantityTensor` a tensor, `Quantity` any shape.""" + if base_type is Quantity or _is_old_pointwise_quantity_union(base_type): + return "any" if base_type is QuantityTensor: return "tensor" return None +_DECLARING_METADATA = (Dimension, Domain, Metadata) + + +def _hides_a_declaration(annotation: object) -> bool: + """Whether a dimensionality, `ABSOLUTE` or required domain sits somewhere Bilt does not read it. + + Bilt reads `Annotated` metadata only at the top of a port's annotation (through plain type aliases). + Metadata inside a union, a generic or a subscripted generic type alias would otherwise be dropped silently. + """ + if isinstance(annotation, typing.TypeAliasType): + return _hides_a_declaration(annotation.__value__) + origin = typing.get_origin(annotation) + if isinstance(origin, typing.TypeAliasType): + return _hides_a_declaration(origin.__value__) or any(map(_hides_a_declaration, typing.get_args(annotation))) + if origin is typing.Annotated: + base_type, *metadata = typing.get_args(annotation) + return any(isinstance(item, _DECLARING_METADATA) or item is ABSOLUTE for item in metadata) or ( + _hides_a_declaration(base_type) + ) + return any(map(_hides_a_declaration, typing.get_args(annotation))) + + def _required_domain( # noqa: PLR0913 owner_name: str, port: str, @@ -86,7 +106,7 @@ def _required_domain( # noqa: PLR0913 ) -> Domain | None: """Read minimum tensor-domain constraints, preserving exact pointwise equation hints.""" # Exact Domain hints on pointwise equations remain for the linear solver. - if dimensionality is None or (not system_boundary and quantity_magnitude_kind(base_type) in ("scalar", "either")): + if dimensionality is None or (not system_boundary and quantity_magnitude_kind(base_type) == "any"): return None domains = [item for item in metadata if isinstance(item, Domain)] @@ -129,9 +149,9 @@ def _reject_dimensioned_tensor_annotation( ) -> None: if dimensionality is not None and base_type is Tensor: msg = ( - "uses the old dimensioned Tensor annotation. " + "declares a dimensionality on Tensor, which has no unit. " "Use Annotated[QuantityTensor, DIM] for a tensor-only port or " - "Annotated[Quantity | QuantityTensor, DIM] for a pointwise port." + "Annotated[Quantity, DIM] for a port of any shape." ) raise BiltPortDeclarationError(owner_name, port, msg) @@ -141,6 +161,14 @@ def _declaration( ) -> PortDeclaration | None: """Classify one annotation, ignoring `Annotated` metadata that is neither a dimensionality nor the absolute marker.""" base_type, metadata = annotated_parts(annotation) + if _hides_a_declaration(base_type): + msg = ( + f"is annotated `{annotation}`, where Bilt cannot read its dimensionality. Put `Annotated` at the top " + "of the annotation, as in `typing.Annotated[Quantity, DIM]`, directly or through a type alias without " + "type parameters. Unions such as `Annotated[...] | None` and subscripted generic aliases such as " + "`Length[Quantity]` are not supported." + ) + raise BiltPortDeclarationError(owner_name, port, msg) unit = next((item for item in metadata if isinstance(item, Unit)), None) if unit is not None: msg = ( @@ -153,7 +181,7 @@ def _declaration( if tag is not None: msg = ( f"declares tag {tag} on its own, but a tag is a factor of a dimensionality. " - "Multiply the dimensionality by it, as in `typing.Annotated[Quantity | QuantityTensor, DIM * tag]`." + "Multiply the dimensionality by it, as in `typing.Annotated[Quantity, DIM * tag]`." ) raise BiltPortDeclarationError(owner_name, port, msg) @@ -175,15 +203,16 @@ def _declaration( if dimensionality is None and (carries_quantity or absolute): msg = ( f"is {'a Quantity' if carries_quantity else 'marked ABSOLUTE'} without a dimensionality. Declare one " - "with `typing.Annotated[Quantity, DIM]` for a scalar, or `typing.Annotated[Quantity | QuantityTensor, DIM]` for a pointwise quantity; write `float` if the port is outside the unit system." + "with `typing.Annotated[Quantity, DIM]`, or `typing.Annotated[QuantityTensor, DIM]` for a tensor-only " + "port; write `Number` (or `float`) if the port is outside the unit system." ) raise BiltPortDeclarationError(owner_name, port, msg) if dimensionality is not None and not (carries_quantity or over_a_domain): msg = ( f"declares {dimensionality} on {getattr(base_type, '__name__', repr(base_type))}, " "but a dimensionality requires a quantity annotation. " - "Use `typing.Annotated[Quantity | QuantityTensor, ...]` on pointwise fields or a concrete " - "Quantity or QuantityTensor annotation for stricter fields and equations." + "Use `typing.Annotated[Quantity, ...]` for any shape or `typing.Annotated[QuantityTensor, ...]` " + "for a tensor-only port." ) raise BiltPortDeclarationError(owner_name, port, msg) @@ -194,7 +223,6 @@ def _declaration( dimensionality, absolute=absolute, over_a_domain=over_a_domain, - scalar_only=magnitude_kind == "scalar", required_domain=required_domain, ) if absolute: diff --git a/src/bilt/core/_system/_errors.py b/src/bilt/core/_system/_errors.py index ad7d66a8..b1186175 100644 --- a/src/bilt/core/_system/_errors.py +++ b/src/bilt/core/_system/_errors.py @@ -15,9 +15,9 @@ import typing from bilt.core._errors import BiltDefinitionError, BiltEvaluationError -from bilt.core._tensors._tensors import Tensor -from bilt.units import Quantity +from bilt.core._tensors._tensors import _Tensor from bilt.units._errors import BiltDimensionalityError +from bilt.units._quantities import _Quantity if typing.TYPE_CHECKING: from bilt.core._port_declaration import PortDeclaration @@ -70,12 +70,12 @@ class BiltInputDimensionalityError(BiltDimensionalityError): def __init__(self, system_name: str, port: str, expected: PortDeclaration | None, value: object) -> None: label = "" match value: - case Quantity(unit=unit): + case _Quantity(unit=unit): received = f"{value} of {unit.dimension}" - case Tensor(unit=unit) if unit is None: + case _Tensor(unit=unit) if unit is None: received = f"a Tensor with no unit over {value.domain}" label = " Label it with `tensor(..., unit=...)`." - case Tensor(unit=unit): + case _Tensor(unit=unit): received = f"a Tensor in {unit} over {value.domain}" case _: unit = None @@ -85,11 +85,11 @@ def __init__(self, system_name: str, port: str, expected: PortDeclaration | None if expected is None: msg = ( f"Input {port!r} of {system_name!r} is a plain port, outside the unit system, so it rejects a " - f"{'unit-carrying Tensor' if isinstance(value, Tensor) else 'Quantity'}: got {received}." + f"{'unit-carrying Tensor' if isinstance(value, _Tensor) else 'Quantity'}: got {received}." ) elif ( expected.required_domain is not None - and isinstance(value, Tensor) + and isinstance(value, _Tensor) and not set(expected.required_domain.dims).issubset(value.domain.dims) ): missing = tuple(dim for dim in expected.required_domain.dims if dim not in value.domain.dims) @@ -97,7 +97,7 @@ def __init__(self, system_name: str, port: str, expected: PortDeclaration | None f"Input {port!r} of {system_name!r} requires domain {expected.required_domain}, " f"but received {value.domain}; missing dimensions: {', '.join(str(dim) for dim in missing)}." ) - elif expected.over_a_domain and not isinstance(value, Tensor): + elif expected.over_a_domain and not isinstance(value, _Tensor): msg = ( f"Input {port!r} of {system_name!r} varies over a domain, so it must be a Tensor of {expected}, " f"not {received}. Annotate it `Quantity` instead if it does not vary over a domain." diff --git a/src/bilt/core/_system/_implementation.py b/src/bilt/core/_system/_implementation.py index 76f5e858..13437a21 100644 --- a/src/bilt/core/_system/_implementation.py +++ b/src/bilt/core/_system/_implementation.py @@ -23,7 +23,7 @@ BiltSubSystemUnreferencedEntryError, ) from bilt.core._system._input_validation import validate_inputs -from bilt.core._tensors._tensors import Tensor +from bilt.core._tensors._tensors import _Tensor from bilt.symbolic._domains import Domain if typing.TYPE_CHECKING: @@ -123,7 +123,7 @@ def evaluate( request = EvaluationRequest( output=output, input_domains={ - name: value.domain if isinstance(value, Tensor) else Domain.scalar() + name: value.domain if isinstance(value, _Tensor) else Domain.scalar() for name, value in inputs.items() }, ) diff --git a/src/bilt/core/_system/_input_validation.py b/src/bilt/core/_system/_input_validation.py index ef0d1d3b..0d9699cf 100644 --- a/src/bilt/core/_system/_input_validation.py +++ b/src/bilt/core/_system/_input_validation.py @@ -4,9 +4,9 @@ from bilt.core._system._errors import BiltInputDimensionalityError from bilt.core._system._sentinel import MISSING -from bilt.core._tensors._tensors import Tensor -from bilt.units import Quantity +from bilt.core._tensors._tensors import _Tensor from bilt.units._category import UnitCategory +from bilt.units._quantities import _Quantity if typing.TYPE_CHECKING: import collections.abc @@ -24,7 +24,7 @@ def validate_inputs( if value is MISSING: continue - unit = value.unit if isinstance(value, Quantity | Tensor) else None + unit = value.unit if isinstance(value, _Quantity | _Tensor) else None expected = declarations.get(port) if expected is None: if unit is not None: @@ -33,11 +33,10 @@ def validate_inputs( unit is None or unit.dimension != expected.dimensionality or not (unit.category is UnitCategory.ABSOLUTE if expected.absolute else unit.is_relative) - or (expected.over_a_domain and not isinstance(value, Tensor)) - or (expected.scalar_only and isinstance(value, Tensor)) + or (expected.over_a_domain and not isinstance(value, _Tensor)) or ( expected.required_domain is not None - and isinstance(value, Tensor) + and isinstance(value, _Tensor) and not set(expected.required_domain.dims).issubset(value.domain.dims) ) ): diff --git a/src/bilt/core/_system/_lowering_and_lifting.py b/src/bilt/core/_system/_lowering_and_lifting.py index 10ad510b..1028a3b8 100644 --- a/src/bilt/core/_system/_lowering_and_lifting.py +++ b/src/bilt/core/_system/_lowering_and_lifting.py @@ -4,8 +4,8 @@ from bilt.core._canonical_ordering import canonicalized from bilt.core._evaluation_context import current_evaluation -from bilt.core._tensors._tensors import Tensor, tensor -from bilt.units import Quantity +from bilt.core._tensors._tensors import _Tensor, tensor +from bilt.units._quantities import _Quantity from bilt.units._units import BASE_UNIT_SYSTEM if TYPE_CHECKING: @@ -30,14 +30,14 @@ def should_lift_into_tensor(self) -> bool: def lower_inputs(inputs: dict[str, object]) -> dict[str, object]: lowered_inputs: dict[str, object] = {} for input_name, input_value in inputs.items(): - if isinstance(input_value, Tensor): + if isinstance(input_value, _Tensor): if input_value.unit is None: lowered_inputs[input_name] = input_value.values else: lowered_inputs[input_name] = BASE_UNIT_SYSTEM.coherent_value( - Quantity(cast("float", input_value.values), input_value.unit) + _Quantity(cast("float", input_value.values), input_value.unit) ) - elif isinstance(input_value, Quantity): + elif isinstance(input_value, _Quantity): lowered_inputs[input_name] = BASE_UNIT_SYSTEM.coherent_value(input_value) else: lowered_inputs[input_name] = input_value @@ -57,7 +57,7 @@ def generate_lifting_plan( ) -def lift_output(output_value: object, lifting_plan: LiftingPlan) -> Tensor | object: +def lift_output(output_value: object, lifting_plan: LiftingPlan) -> _Tensor | object: if lifting_plan.squeezed_axes: output_value = _squeeze_axes(output_value, lifting_plan.squeezed_axes) if lifting_plan.should_lift_into_tensor: @@ -67,7 +67,7 @@ def lift_output(output_value: object, lifting_plan: LiftingPlan) -> Tensor | obj unit=lifting_plan.output_unit, ) elif lifting_plan.output_unit is not None: - output_value = Quantity(float(cast("SupportsFloat", output_value)), lifting_plan.output_unit) + output_value = _Quantity(float(cast("SupportsFloat", output_value)), lifting_plan.output_unit) return output_value diff --git a/src/bilt/core/_tensors/_protocols.py b/src/bilt/core/_tensors/_protocols.py new file mode 100644 index 00000000..d6ad1694 --- /dev/null +++ b/src/bilt/core/_tensors/_protocols.py @@ -0,0 +1,168 @@ +"""The public `Tensor`, `QuantityTensor` and `Number` annotations. + +Together with `Quantity` they answer two independent questions about a port: + +| | Any shape | Must be a tensor | +|----------|------------|------------------| +| Units | `Quantity` | `QuantityTensor` | +| No units | `Number` | `Tensor` | +""" + +__all__ = ["Number", "QuantityTensor", "Tensor"] + +import typing + +from bilt.units._protocols import Quantity + +if typing.TYPE_CHECKING: + import numpy as np + + from bilt.symbolic._dimensions import Coordinate, Dim + from bilt.symbolic._domains import Domain + + +class _Tensorial(typing.Protocol): + """What every tensor has, with or without a unit: a domain to reduce and select along.""" + + @property + def values(self) -> np.ndarray: + """The values, with one array axis per dimension of the domain.""" + ... + + @property + def domain(self) -> Domain: + """The named dimensions the values vary over.""" + ... + + @property + def shape(self) -> tuple[int, ...]: + """The length of each dimension of the domain.""" + ... + + @property + def ndim(self) -> int: + """The number of dimensions of the domain.""" + ... + + def __float__(self) -> float: + """The value of a tensor with no dimensions; any other tensor raises `TypeError`.""" + ... + + def sum(self, dim: Dim, /) -> typing.Self: + """The sum over a named dimension.""" + ... + + def mean(self, dim: Dim, /) -> typing.Self: + """The mean over a named dimension.""" + ... + + def min(self, dim: Dim, /) -> typing.Self: + """The minimum over a named dimension.""" + ... + + def max(self, dim: Dim, /) -> typing.Self: + """The maximum over a named dimension.""" + ... + + def prod(self, dim: Dim, /) -> typing.Self: + """The product over a named dimension.""" + ... + + def isel(self, dim: Dim, index: int, /) -> typing.Self: + """The values at a position along a named dimension.""" + ... + + def sel(self, dim: Dim, coordinate: Coordinate, /) -> typing.Self: + """The values at a coordinate along a named dimension.""" + ... + + +@typing.runtime_checkable +class Tensor(_Tensorial, typing.Protocol): + """Unitless values over named dimensions, which an equation can reduce or select along. + + Create one with `tensor(...)`. A tensor with a unit is a `QuantityTensor` instead. + """ + + def __add__(self, other: typing.Self | float, /) -> typing.Self: ... + + def __radd__(self, other: float, /) -> typing.Self: ... + + def __sub__(self, other: typing.Self | float, /) -> typing.Self: ... + + def __rsub__(self, other: float, /) -> typing.Self: ... + + @typing.overload + def __mul__(self, other: Quantity, /) -> QuantityTensor: ... + + @typing.overload + def __mul__(self, other: typing.Self | float, /) -> typing.Self: ... + + @typing.overload + def __rmul__(self, other: Quantity, /) -> QuantityTensor: ... + + @typing.overload + def __rmul__(self, other: float, /) -> typing.Self: ... + + @typing.overload + def __truediv__(self, other: Quantity, /) -> QuantityTensor: ... + + @typing.overload + def __truediv__(self, other: typing.Self | float, /) -> typing.Self: ... + + @typing.overload + def __rtruediv__(self, other: Quantity, /) -> QuantityTensor: ... + + @typing.overload + def __rtruediv__(self, other: float, /) -> typing.Self: ... + + def __pow__(self, other: float, /) -> typing.Self: ... + + def __pos__(self) -> typing.Self: ... + + def __neg__(self) -> typing.Self: ... + + def __abs__(self) -> typing.Self: ... + + def __lt__(self, other: typing.Self | float, /) -> bool: ... + + def __le__(self, other: typing.Self | float, /) -> bool: ... + + def __gt__(self, other: typing.Self | float, /) -> bool: ... + + def __ge__(self, other: typing.Self | float, /) -> bool: ... + + +@typing.runtime_checkable +class QuantityTensor(Quantity, _Tensorial, typing.Protocol): + """A tensor of quantities: values with a unit over named dimensions. + + Create one with `tensor(..., unit=...)`, or by multiplying a tensor by a unit. + """ + + @property + def value(self) -> Tensor: + """The unitless magnitude, over the same domain.""" + ... + + # A scalar quantity or a unitless tensor combines with a quantity tensor to give a quantity tensor. + + def __add__(self, other: Quantity, /) -> typing.Self: ... + + def __radd__(self, other: Quantity, /) -> typing.Self: ... + + def __sub__(self, other: Quantity, /) -> typing.Self: ... + + def __rsub__(self, other: Quantity, /) -> typing.Self: ... + + def __mul__(self, other: Quantity | Tensor | float, /) -> typing.Self: ... + + def __rmul__(self, other: Quantity | Tensor | float, /) -> typing.Self: ... + + def __truediv__(self, other: Quantity | Tensor | float, /) -> typing.Self: ... + + def __rtruediv__(self, other: Quantity | Tensor | float, /) -> typing.Self: ... + + +Number = float | Tensor +"""A unitless value of any shape: a number or a unitless tensor.""" diff --git a/src/bilt/core/_tensors/_tensor_alignment.py b/src/bilt/core/_tensors/_tensor_alignment.py index 8459a02e..7feee7d5 100644 --- a/src/bilt/core/_tensors/_tensor_alignment.py +++ b/src/bilt/core/_tensors/_tensor_alignment.py @@ -1,7 +1,7 @@ import dataclasses from bilt.core._evaluation_context import current_evaluation -from bilt.core._tensors._tensors import Tensor +from bilt.core._tensors._tensors import _Tensor @dataclasses.dataclass(frozen=True) @@ -11,7 +11,7 @@ class AlignmentPlan: def generate_alignment_plan(inputs: dict[str, object]) -> AlignmentPlan: tensor_inputs = { - input_name: input_value for input_name, input_value in inputs.items() if isinstance(input_value, Tensor) + input_name: input_value for input_name, input_value in inputs.items() if isinstance(input_value, _Tensor) } canonical_ordering = current_evaluation().canonical_order diff --git a/src/bilt/core/_tensors/_tensors.py b/src/bilt/core/_tensors/_tensors.py index a96e4b0d..176006f8 100644 --- a/src/bilt/core/_tensors/_tensors.py +++ b/src/bilt/core/_tensors/_tensors.py @@ -1,7 +1,5 @@ __all__ = [ "OverArg", - "QuantityTensor", - "Tensor", "tensor", ] @@ -18,12 +16,17 @@ from bilt.units._conversion import conversion_between from bilt.units._errors import BiltUnitError from bilt.units._units import Unit +from bilt.units._validation import validate_cast + +if typing.TYPE_CHECKING: + from bilt.core._tensors._protocols import QuantityTensor, Tensor + from bilt.units._protocols import Quantity OverArg = Dim | collections.abc.Iterable[Dim] -@dataclasses.dataclass(frozen=True, slots=True) -class Tensor: +@dataclasses.dataclass(frozen=True, slots=True, repr=False) +class _Tensor: """Concrete values over a Bilt domain.""" values: np.ndarray @@ -37,7 +40,7 @@ def __post_init__(self) -> None: _check_rank(values, self.domain) @classmethod - def scalar(cls, value: object, unit: Unit | None = None) -> Tensor: + def scalar(cls, value: object, unit: Unit | None = None) -> _Tensor: values = np.asarray(value) if values.ndim != 0: @@ -50,6 +53,12 @@ def scalar(cls, value: object, unit: Unit | None = None) -> Tensor: unit=unit, ) + def __repr__(self) -> str: + # Named after the public annotation the value satisfies; the class itself is private. + if self.unit is None: + return f"Tensor(values={self.values!r}, domain={self.domain!r})" + return f"QuantityTensor(values={self.values!r}, domain={self.domain!r}, unit={self.unit!r})" + @property def shape(self) -> tuple[int, ...]: return self.values.shape @@ -58,36 +67,67 @@ def shape(self) -> tuple[int, ...]: def ndim(self) -> int: return self.values.ndim - def __add__(self, other: object) -> Tensor: + def __float__(self) -> float: + """The value of a tensor with no dimensions; any other tensor raises `TypeError`, as in NumPy.""" + return float(self.values) + + # Arithmetic is symbolic: these methods exist to type equation bodies and raise outside a model. + # A unitless tensor stays unitless unless a quantity or a unit joins it. + + @typing.overload + def __add__(self, other: Quantity) -> _QuantityTensor: ... + + @typing.overload + def __add__(self, other: object) -> _Tensor: ... + + def __add__(self, other: object) -> _Tensor: raise _arithmetic_not_implemented() - def __radd__(self, other: object) -> Tensor: + @typing.overload + def __radd__(self, other: Quantity) -> _QuantityTensor: ... + + @typing.overload + def __radd__(self, other: object) -> _Tensor: ... + + def __radd__(self, other: object) -> _Tensor: raise _arithmetic_not_implemented() - def __sub__(self, other: object) -> Tensor: + @typing.overload + def __sub__(self, other: Quantity) -> _QuantityTensor: ... + + @typing.overload + def __sub__(self, other: object) -> _Tensor: ... + + def __sub__(self, other: object) -> _Tensor: raise _arithmetic_not_implemented() - def __rsub__(self, other: object) -> Tensor: + @typing.overload + def __rsub__(self, other: Quantity) -> _QuantityTensor: ... + + @typing.overload + def __rsub__(self, other: object) -> _Tensor: ... + + def __rsub__(self, other: object) -> _Tensor: raise _arithmetic_not_implemented() @typing.overload - def __mul__(self, other: Unit) -> QuantityTensor: ... + def __mul__(self, other: Unit | Quantity) -> _QuantityTensor: ... @typing.overload - def __mul__(self, other: object) -> Tensor: ... + def __mul__(self, other: object) -> _Tensor: ... - def __mul__(self, other: object) -> Tensor: + def __mul__(self, other: object) -> _Tensor: if isinstance(other, Unit): return self._labelled(other if self.unit is None else self.unit * other) raise _arithmetic_not_implemented() @typing.overload - def __rmul__(self, other: Unit) -> QuantityTensor: ... + def __rmul__(self, other: Unit | Quantity) -> _QuantityTensor: ... @typing.overload - def __rmul__(self, other: object) -> Tensor: ... + def __rmul__(self, other: object) -> _Tensor: ... - def __rmul__(self, other: object) -> Tensor: + def __rmul__(self, other: object) -> _Tensor: if isinstance(other, Unit): if self.unit is None: return NotImplemented @@ -95,49 +135,79 @@ def __rmul__(self, other: object) -> Tensor: raise _arithmetic_not_implemented() @typing.overload - def __truediv__(self, other: Unit) -> QuantityTensor: ... + def __truediv__(self, other: Unit | Quantity) -> _QuantityTensor: ... @typing.overload - def __truediv__(self, other: object) -> Tensor: ... + def __truediv__(self, other: object) -> _Tensor: ... - def __truediv__(self, other: object) -> Tensor: + def __truediv__(self, other: object) -> _Tensor: if isinstance(other, Unit): if self.unit is None: return NotImplemented return self._labelled(self.unit / other) raise _arithmetic_not_implemented() - def __rtruediv__(self, other: object) -> Tensor: + @typing.overload + def __rtruediv__(self, other: Quantity) -> _QuantityTensor: ... + + @typing.overload + def __rtruediv__(self, other: object) -> _Tensor: ... + + def __rtruediv__(self, other: object) -> _Tensor: + raise _arithmetic_not_implemented() + + def __pow__(self, other: float | Tensor | Quantity) -> typing.Self: + raise _arithmetic_not_implemented() + + def __rpow__(self, other: float | Quantity) -> typing.Self: + raise _arithmetic_not_implemented() + + def __pos__(self) -> typing.Self: + raise _arithmetic_not_implemented() + + def __neg__(self) -> typing.Self: raise _arithmetic_not_implemented() - def __neg__(self) -> Tensor: + def __abs__(self) -> typing.Self: raise _arithmetic_not_implemented() - def mean(self, dim: Dim) -> Tensor: # noqa: ARG002 + def __lt__(self, other: object) -> bool: + raise _symbolic_operation_only() + + def __le__(self, other: object) -> bool: + raise _symbolic_operation_only() + + def __gt__(self, other: object) -> bool: + raise _symbolic_operation_only() + + def __ge__(self, other: object) -> bool: + raise _symbolic_operation_only() + + def mean(self, dim: Dim) -> typing.Self: # noqa: ARG002 """Return the mean over a named dimension in a Bilt model.""" raise _symbolic_operation_only() - def sum(self, dim: Dim) -> Tensor: # noqa: ARG002 + def sum(self, dim: Dim) -> typing.Self: # noqa: ARG002 """Return the sum over a named dimension in a Bilt model.""" raise _symbolic_operation_only() - def min(self, dim: Dim) -> Tensor: # noqa: ARG002 + def min(self, dim: Dim) -> typing.Self: # noqa: ARG002 """Return the minimum over a named dimension in a Bilt model.""" raise _symbolic_operation_only() - def max(self, dim: Dim) -> Tensor: # noqa: ARG002 + def max(self, dim: Dim) -> typing.Self: # noqa: ARG002 """Return the maximum over a named dimension in a Bilt model.""" raise _symbolic_operation_only() - def prod(self, dim: Dim) -> Tensor: # noqa: ARG002 + def prod(self, dim: Dim) -> typing.Self: # noqa: ARG002 """Return the product over a named dimension in a Bilt model.""" raise _symbolic_operation_only() - def isel(self, dim: Dim, index: int) -> Tensor: # noqa: ARG002 + def isel(self, dim: Dim, index: int) -> typing.Self: # noqa: ARG002 """Select a position along a named dimension in a Bilt model.""" raise _symbolic_operation_only() - def sel(self, dim: Dim, coordinate: Coordinate) -> Tensor: # noqa: ARG002 + def sel(self, dim: Dim, coordinate: Coordinate) -> typing.Self: # noqa: ARG002 """Select a coordinate along a named dimension in a Bilt model.""" raise _symbolic_operation_only() @@ -160,31 +230,79 @@ def convert_to(self, unit: Unit) -> typing.Self: return dataclasses.replace(self, values=self.values * conversion.scale + conversion.offset, unit=unit) - def _labelled(self, unit: Unit) -> QuantityTensor: - return QuantityTensor(values=self.values, domain=self.domain, unit=unit) + def _labelled(self, unit: Unit) -> _QuantityTensor: + return _QuantityTensor(values=self.values, domain=self.domain, unit=unit) -@dataclasses.dataclass(frozen=True, slots=True, kw_only=True) -class QuantityTensor(Tensor): +@dataclasses.dataclass(frozen=True, slots=True, kw_only=True, repr=False) +class _QuantityTensor(_Tensor): """Unit-bearing tensor with a non-optional unit and a quantity magnitude. - It retains the Tensor API, including symbolic operations, domains, - conversion and unit composition. Its `value` is a unitless Tensor + It retains the _Tensor API, including symbolic operations, domains, + conversion and unit composition. Its `value` is a unitless _Tensor retaining the original domain. """ unit: Unit def __post_init__(self) -> None: - Tensor.__post_init__(self) + _Tensor.__post_init__(self) if not isinstance(self.unit, Unit): message = "QuantityTensor requires a physical unit" raise BiltUnitError(message) + # Scaling by a number or a unitless tensor keeps the unit; the base class already types + # addition and subtraction with quantities as returning a quantity tensor. + + @typing.overload + def __mul__(self, other: Unit | Tensor | Quantity | float) -> _QuantityTensor: ... + + @typing.overload + def __mul__(self, other: object) -> _Tensor: ... + + def __mul__(self, other: object) -> _Tensor: + return _Tensor.__mul__(self, other) + + @typing.overload + def __rmul__(self, other: Unit | Tensor | Quantity | float) -> _QuantityTensor: ... + + @typing.overload + def __rmul__(self, other: object) -> _Tensor: ... + + def __rmul__(self, other: object) -> _Tensor: + return _Tensor.__rmul__(self, other) + + @typing.overload + def __truediv__(self, other: Unit | Tensor | Quantity | float) -> _QuantityTensor: ... + + @typing.overload + def __truediv__(self, other: object) -> _Tensor: ... + + def __truediv__(self, other: object) -> _Tensor: + return _Tensor.__truediv__(self, other) + + @typing.overload + def __rtruediv__(self, other: Tensor | Quantity | float) -> _QuantityTensor: ... + + @typing.overload + def __rtruediv__(self, other: object) -> _Tensor: ... + + def __rtruediv__(self, other: object) -> _Tensor: + return _Tensor.__rtruediv__(self, other) + + def cast_to(self, unit: Unit) -> typing.Self: + """Relabel these values with an equivalent `unit`, without converting them.""" + validate_cast(self, unit) + return dataclasses.replace(self, unit=unit) + + def strip_metadata(self) -> typing.Self: + """Return these values with every metadata tag removed from their unit.""" + return dataclasses.replace(self, unit=self.unit.strip_metadata()) + @property - def value(self) -> Tensor: + def value(self) -> _Tensor: """The unitless magnitude, retaining the original tensor domain.""" - return Tensor(values=self.values, domain=self.domain) + return _Tensor(values=self.values, domain=self.domain) @typing.overload @@ -202,7 +320,7 @@ def tensor( @typing.overload def tensor( values: object, *, over: OverArg | None = None, domain: Domain | None = None, unit: Unit | None -) -> Tensor: ... +) -> Tensor | QuantityTensor: ... def tensor( @@ -211,7 +329,7 @@ def tensor( over: OverArg | None = None, domain: Domain | None = None, unit: Unit | None = None, -) -> Tensor: +) -> Tensor | QuantityTensor: """Create a Bilt tensor from concrete user data. Scalars may omit a domain. Non-scalar values must provide either @@ -230,9 +348,9 @@ def tensor( domain = _domain_from_over(over) case None, None if array.ndim == 0: return ( - QuantityTensor(values=array, domain=Domain.scalar(), unit=unit) + _QuantityTensor(values=array, domain=Domain.scalar(), unit=unit) if unit is not None - else Tensor.scalar(array) + else _Tensor.scalar(array) ) case None, None: message = "Non-scalar values need an explicit domain" @@ -242,9 +360,9 @@ def tensor( raise BiltTensorDomainError(message) return ( - QuantityTensor(values=array, domain=domain, unit=unit) + _QuantityTensor(values=array, domain=domain, unit=unit) if unit is not None - else Tensor(values=array, domain=domain) + else _Tensor(values=array, domain=domain) ) diff --git a/src/bilt/core/_unit_erasure.py b/src/bilt/core/_unit_erasure.py index 696734c9..a358d6f6 100644 --- a/src/bilt/core/_unit_erasure.py +++ b/src/bilt/core/_unit_erasure.py @@ -9,10 +9,11 @@ from collections import Counter from bilt.core._errors import BiltDefinitionError -from bilt.units import Dimension, Metadata, Quantity, Unit +from bilt.units import Dimension, Metadata, Unit from bilt.units._category import UnitCategory from bilt.units._conversion import conversion_between from bilt.units._errors import BiltUnitError +from bilt.units._quantities import _Quantity from bilt.units._units import BASE_UNIT_SYSTEM if typing.TYPE_CHECKING: @@ -22,7 +23,7 @@ from bilt.core._transform import BasicTransform from bilt.units._conversion import Conversion -_UNIT_TYPES = (Quantity, Unit, Dimension) +_UNIT_TYPES = (_Quantity, Unit, Dimension) _QUANTITY_ATTRIBUTES = frozenset({"value", "unit", "convert_to", "cast_to", "strip_metadata"}) @@ -245,16 +246,7 @@ def _erased(self, node: ast.expr) -> ast.expr: # noqa: C901, PLR0911 ) raise BiltDefinitionError(msg) return self._erased(quantity) - case ( - ast.Call(func=function, args=[value, unit], keywords=[]) - | ast.Call(func=function, args=[value], keywords=[ast.keyword(arg="unit", value=unit)]) - | ast.Call( - func=function, - args=[], - keywords=[ast.keyword(arg="value", value=value), ast.keyword(arg="unit", value=unit)] - | [ast.keyword(arg="unit", value=unit), ast.keyword(arg="value", value=value)], - ) - ) if self._resolved(function) is Quantity: + case ast.BinOp(left=value, op=ast.Mult(), right=unit) if self._makes_an_absolute_quantity(value, unit): conversion = self._conversion(unit, node) coherent = ast.BinOp(left=self._erased(value), op=ast.Mult(), right=ast.Constant(conversion.scale)) if conversion.offset: @@ -281,16 +273,18 @@ def _is_constant(self, node: ast.expr) -> bool: # noqa: PLR0911 return False value = self.bindings[name] - return type(value) in (bool, int, float) or isinstance(value, (Quantity, Unit, Dimension, Metadata)) + return type(value) in (bool, int, float) or isinstance(value, (_Quantity, Unit, Dimension, Metadata)) case ast.Attribute(value=root): # Resolve named constants through imported modules. if isinstance(self._resolved(root), types.ModuleType): value = self._resolved(node) - return type(value) in (bool, int, float) or isinstance(value, (Quantity, Unit, Dimension, Metadata)) + return type(value) in (bool, int, float) or isinstance( + value, (_Quantity, Unit, Dimension, Metadata) + ) # Supported, read-only properties on known Bilt constants. - return isinstance(self._resolved(root), (Quantity, Unit, Dimension)) and node.attr in { + return isinstance(self._resolved(root), (_Quantity, Unit, Dimension)) and node.attr in { "value", "dimension", "is_dimensionless", @@ -308,18 +302,18 @@ def _is_constant(self, node: ast.expr) -> bool: # noqa: PLR0911 ): return self._is_constant(left) and self._is_constant(right) - case ast.Call(func=function, args=args, keywords=keywords): - return ( - self._resolved(function) is Quantity - and all(self._is_constant(arg) for arg in args) - and all( - keyword.arg in {"value", "unit"} and self._is_constant(keyword.value) for keyword in keywords - ) - ) - case _: return False + def _makes_an_absolute_quantity(self, value: ast.expr, unit: ast.expr) -> bool: + """Whether `value * unit` reads a plain number as a reading in an absolute unit, such as `degrees * absolute_celsius`.""" + if not self._is_constant(unit) or self._is_constant(value): + return False + resolved = self._evaluated(unit) + if not (isinstance(resolved, Unit) and resolved.category is UnitCategory.ABSOLUTE): + return False + return not (isinstance(value, ast.Name) and value.id in self.declared_parameters and value not in self.shadowed) + def _reaches_a_unit(self, node: ast.expr) -> bool: """Whether `node` names a quantity, a unit or a dimensionality, or one of their classes.""" return any( @@ -366,11 +360,11 @@ def _literal(self, node: ast.expr, value: object) -> ast.expr: case Unit(category=UnitCategory.ABSOLUTE): problem = ( "is an absolute unit, which cannot be used as a scale: " - f"write `Quantity(, {ast.unparse(node)})`" + f"multiply a plain number by it, as in ` * {ast.unparse(node)}`" ) case Unit(): - return self._literal(node, Quantity(1.0, value)) - case Quantity(): + return self._literal(node, _Quantity(1.0, value)) + case _Quantity(): return ast.Constant(BASE_UNIT_SYSTEM.coherent_value(value)) case bool() | int() | float(): return ast.Constant(value) diff --git a/src/bilt/symbolic/_expressions.py b/src/bilt/symbolic/_expressions.py index d828c21c..ba1d5e7f 100644 --- a/src/bilt/symbolic/_expressions.py +++ b/src/bilt/symbolic/_expressions.py @@ -28,8 +28,9 @@ sum_tree, symbol_tree, ) -from bilt.units import Metadata, Quantity, Unit +from bilt.units import Metadata, Unit from bilt.units._category import UnitCategory +from bilt.units._quantities import _Quantity from bilt.units._units import BASE_UNIT_SYSTEM if typing.TYPE_CHECKING: @@ -311,7 +312,7 @@ def as_tree(value: object) -> Tree: if isinstance(value, float): return float_tree(value) - if isinstance(value, Quantity): + if isinstance(value, _Quantity): return quantity_tree( BASE_UNIT_SYSTEM.coherent_value(value), value.unit.dimension, @@ -325,7 +326,7 @@ def as_tree(value: object) -> Tree: f"Use its relative unit '{value.relation}' instead." ) raise BiltSymbolicConversionError(msg) - return as_tree(Quantity(1.0, value)) + return as_tree(_Quantity(1.0, value)) if isinstance(value, Metadata): msg = ( diff --git a/src/bilt/units/__init__.py b/src/bilt/units/__init__.py index a9494805..a813540b 100644 --- a/src/bilt/units/__init__.py +++ b/src/bilt/units/__init__.py @@ -99,7 +99,7 @@ from ._currencies import USD as USD from ._metadata import Metadata as Metadata from ._prefix import Prefix as Prefix -from ._quantities import Quantity as Quantity +from ._protocols import Quantity as Quantity from ._units import Unit as Unit from .dimensions._dimensions import Dimension as Dimension from .units import UNITLESS as UNITLESS diff --git a/src/bilt/units/_metadata.py b/src/bilt/units/_metadata.py index 7a4da48a..93cce27f 100644 --- a/src/bilt/units/_metadata.py +++ b/src/bilt/units/_metadata.py @@ -2,10 +2,13 @@ from bilt.units._errors import BiltMetadataError -from ._quantities import Quantity +from ._quantities import _Quantity from ._units import Unit, UnitComposition, UnitOrder from .dimensions._dimensions import Dimension +if typing.TYPE_CHECKING: + from bilt.units._protocols import Quantity + @typing.final class Metadata: @@ -39,15 +42,15 @@ def __rmul__(self, other: Dimension) -> Dimension: ... def __rmul__(self, other: Unit) -> Unit: ... @typing.overload - def __rmul__(self, other: Quantity) -> Quantity: ... + def __rmul__[Q: Quantity](self, other: Q) -> Q: ... - def __rmul__(self, other: Dimension | Unit | Quantity) -> Dimension | Unit | Quantity: + def __rmul__(self, other: object) -> object: if isinstance(other, Dimension): return Dimension(tagged={(other, self): 1}) if isinstance(other, Unit): return Unit(UnitComposition(UnitOrder(other, 1)), metadata=self) - if isinstance(other, Quantity): - return Quantity(other.value, other.unit * self) + if isinstance(other, _Quantity): + return _Quantity(other.value, other.unit * self) return NotImplemented def __lt__(self, other: Metadata | None) -> bool: diff --git a/src/bilt/units/_protocols.py b/src/bilt/units/_protocols.py new file mode 100644 index 00000000..352d453b --- /dev/null +++ b/src/bilt/units/_protocols.py @@ -0,0 +1,67 @@ +"""The public `Quantity` protocol: what a value with a unit can do, whatever its shape.""" + +import typing + +if typing.TYPE_CHECKING: + from bilt.core._tensors._protocols import Number + from bilt.units._units import Unit + + +@typing.runtime_checkable +class Quantity(typing.Protocol): + """A value with a unit, of any shape: a scalar quantity or a tensor of quantities. + + Annotate a port `typing.Annotated[Quantity, DIM]` to accept either. Create one by + multiplying a number by a unit, as in `2.0 * kilogram`, or with + `tensor(..., unit=...)`. + """ + + @property + def unit(self) -> Unit: + """The unit the value is expressed in.""" + ... + + @property + def value(self) -> Number: + """The unitless magnitude: a number for a scalar, a tensor for a tensor.""" + ... + + def convert_to(self, unit: Unit, /) -> typing.Self: + """Return the same quantity expressed in `unit`.""" + ... + + def cast_to(self, unit: Unit, /) -> typing.Self: + """Relabel the same numbers with an equivalent `unit`, without converting them.""" + ... + + def strip_metadata(self) -> typing.Self: + """Return the same quantity with every metadata tag removed from its unit.""" + ... + + def __add__(self, other: typing.Self, /) -> typing.Self: ... + + def __sub__(self, other: typing.Self, /) -> typing.Self: ... + + def __mul__(self, other: typing.Self | float, /) -> typing.Self: ... + + def __rmul__(self, other: float, /) -> typing.Self: ... + + def __truediv__(self, other: typing.Self | float, /) -> typing.Self: ... + + def __rtruediv__(self, other: float, /) -> typing.Self: ... + + def __pow__(self, other: float | Quantity, /) -> typing.Self: ... + + def __pos__(self) -> typing.Self: ... + + def __neg__(self) -> typing.Self: ... + + def __abs__(self) -> typing.Self: ... + + def __lt__(self, other: typing.Self, /) -> bool: ... + + def __le__(self, other: typing.Self, /) -> bool: ... + + def __gt__(self, other: typing.Self, /) -> bool: ... + + def __ge__(self, other: typing.Self, /) -> bool: ... diff --git a/src/bilt/units/_quantities.py b/src/bilt/units/_quantities.py index 2db8406d..9197ff6f 100644 --- a/src/bilt/units/_quantities.py +++ b/src/bilt/units/_quantities.py @@ -7,12 +7,13 @@ from bilt.units._validation import validate_addition, validate_cast, validate_comparison if typing.TYPE_CHECKING: + from bilt.units._protocols import Quantity from bilt.units._units import Unit @typing.final @functools.total_ordering -class Quantity: +class _Quantity: __slots__ = ("_unit", "_value") _value: float @@ -34,13 +35,13 @@ def cast_to(self, unit: Unit) -> typing.Self: validate_cast(self, unit) return self.__class__(self.value, unit) - def convert_to(self, unit: Unit) -> Quantity: + def convert_to(self, unit: Unit) -> _Quantity: if self.unit.category is UnitCategory.ABSOLUTE and self.unit is unit: return self conversion = conversion_between(self.unit, unit) - return Quantity( + return _Quantity( conversion.apply(self.value), unit, ) @@ -57,7 +58,7 @@ def __neg__(self) -> typing.Self: def __abs__(self) -> typing.Self: return self.__class__(abs(self.value), self.unit) - def __add__(self, other: Quantity) -> typing.Self: + def __add__(self, other: _Quantity) -> typing.Self: if not isinstance(other, self.__class__): return NotImplemented @@ -75,15 +76,15 @@ def __add__(self, other: Quantity) -> typing.Self: unit, ) - def __radd__(self, other: int) -> Quantity: + def __radd__(self, other: int) -> _Quantity: if not isinstance(other, int) and other != 0: return NotImplemented return self - def __sub__(self, other: Quantity) -> Quantity: + def __sub__(self, other: _Quantity) -> _Quantity: if self.unit.category is UnitCategory.ABSOLUTE and other.unit.category is UnitCategory.ABSOLUTE: - return (self.value * self.unit.relation.composition[0].unit) + ( - -other.value * other.unit.relation.composition[0].unit + return _Quantity(self.value, self.unit.relation.composition[0].unit) + _Quantity( + -other.value, other.unit.relation.composition[0].unit ) if isinstance(other, self.__class__) and other.unit.category is UnitCategory.ABSOLUTE: message = ( @@ -93,7 +94,7 @@ def __sub__(self, other: Quantity) -> Quantity: raise BiltUnitError(message) return self + (-other) - def __mul__(self, other: Quantity | float) -> typing.Self: + def __mul__(self, other: _Quantity | float) -> typing.Self: if isinstance(other, self.__class__): return self.__class__(self.value * other.value, self.unit * other.unit) if isinstance(other, float): @@ -105,7 +106,7 @@ def __rmul__(self, other: float) -> typing.Self: return NotImplemented return self.__class__(self.value * other, self.unit) - def __truediv__(self, other: Quantity | float) -> typing.Self: + def __truediv__(self, other: _Quantity | float) -> typing.Self: if isinstance(other, self.__class__): return self.__class__(self.value / other.value, self.unit / other.unit) if isinstance(other, float): @@ -123,7 +124,7 @@ def __pow__(self, other: float | Quantity) -> typing.Self: return self.__class__(self.value**other, self.unit**other) case float() if self.unit.is_dimensionless: return self.__class__(self.value**other, self.unit) - case Quantity() if self.unit.is_dimensionless and self.unit.relation.scale == 1.0: + case _Quantity() if self.unit.is_dimensionless and self.unit.relation.scale == 1.0: return self.__class__(self.value**other.value, self.unit) return NotImplemented @@ -153,4 +154,4 @@ def __str__(self) -> str: return f"{self.value!s} {self.unit!s}" def __repr__(self) -> str: - return f"{self.__class__.__name__}(value={self.value!r}, unit={self.unit!r})" + return f"Quantity(value={self.value!r}, unit={self.unit!r})" diff --git a/src/bilt/units/_units.py b/src/bilt/units/_units.py index 8bec4c97..ab12837f 100644 --- a/src/bilt/units/_units.py +++ b/src/bilt/units/_units.py @@ -7,7 +7,7 @@ from ._category import UnitCategory from ._prefix import PREFIX_NAMES, Prefix -from ._quantities import Quantity +from ._quantities import _Quantity from .dimensions._dimensions import ( AMOUNT, CURRENCY, @@ -21,6 +21,9 @@ ) if typing.TYPE_CHECKING: + from bilt.core._tensors._protocols import QuantityTensor, Tensor + from bilt.units._protocols import Quantity + from ._metadata import Metadata @@ -305,7 +308,7 @@ def new_named( relation = relation.relation case UnitComposition(): pass - case Quantity(): + case _Quantity(): quantity = relation if quantity.unit.metadata is not None or quantity.unit.category in ( UnitCategory.BASE, @@ -321,7 +324,8 @@ def new_named( scale=quantity.value * quantity.unit.relation.scale, ) case _: - typing.assert_never(relation) + message = f"Unit {name!r} must be defined by a unit or a scalar quantity, not {relation!r}" + raise BiltUnitError(message) if relation is UnitComposition(UnitOrder(kilogram, 1)): prefix_scale = 0.001 if prefix is None else 10 ** (prefix.value - 3) @@ -370,12 +374,13 @@ def new_absolute( relation = UnitComposition(UnitOrder(scale, 1)) offset: UnitComposition | None match zero: - case Quantity(): + case _Quantity(): offset = UnitComposition(UnitOrder(zero.unit, 1), scale=zero.value) case None: offset = None case _: - typing.assert_never(zero) + message = f"Absolute unit {name!r} must have a scalar quantity as its zero, not {zero!r}" + raise BiltUnitError(message) key = (name, relation, metadata) if key in cls._cache: instance = cls._cache[key] @@ -488,9 +493,12 @@ def __abs__(self) -> Unit: def __mul__(self, other: Unit) -> typing.Self: ... @typing.overload - def __mul__(self, other: Quantity) -> Quantity: ... + def __mul__[Q: Quantity](self, other: Q) -> Q: ... - def __mul__(self, other: Unit | Quantity) -> typing.Self | Quantity: + @typing.overload + def __mul__(self, other: Tensor) -> QuantityTensor: ... + + def __mul__(self, other: object) -> object: if isinstance(other, self.__class__): left = ( self.relation @@ -503,24 +511,33 @@ def __mul__(self, other: Unit | Quantity) -> typing.Self | Quantity: else UnitComposition(UnitOrder(other, 1)) ) return self.__class__(left * right) - if isinstance(other, Quantity): - return Quantity(other.value, self * other.unit) + if isinstance(other, _Quantity): + return _Quantity(other.value, self * other.unit) return NotImplemented - def __rmul__(self, other: Quantity | float) -> Quantity: - if isinstance(other, Quantity): - return Quantity(other.value, other.unit * self) - if isinstance(other, float): - return Quantity(other, self) + @typing.overload + def __rmul__(self, other: float) -> Quantity: ... + + @typing.overload + def __rmul__[Q: Quantity](self, other: Q) -> Q: ... + + @typing.overload + def __rmul__(self, other: Tensor) -> QuantityTensor: ... + + def __rmul__(self, other: object) -> object: + if isinstance(other, _Quantity): + return _Quantity(other.value, other.unit * self) + if isinstance(other, int | float) and not isinstance(other, bool): + return _Quantity(float(other), self) return NotImplemented @typing.overload def __truediv__(self, other: Unit) -> typing.Self: ... @typing.overload - def __truediv__(self, other: Quantity) -> Quantity: ... + def __truediv__[Q: Quantity](self, other: Q) -> Q: ... - def __truediv__(self, other: Unit | Quantity) -> typing.Self | Quantity: + def __truediv__(self, other: object) -> object: if isinstance(other, self.__class__): numerator = ( self.relation @@ -533,19 +550,22 @@ def __truediv__(self, other: Unit | Quantity) -> typing.Self | Quantity: else UnitComposition(UnitOrder(other, 1)) ) return self.__class__(numerator / denominator) - if isinstance(other, Quantity): - return Quantity(1.0 / other.value, self / other.unit) + if isinstance(other, _Quantity): + return _Quantity(1.0 / other.value, self / other.unit) return NotImplemented @typing.overload def __rtruediv__(self, other: typing.Literal[1]) -> typing.Self: ... @typing.overload - def __rtruediv__(self, other: Quantity) -> Quantity: ... + def __rtruediv__[Q: Quantity](self, other: Q) -> Q: ... + + @typing.overload + def __rtruediv__(self, other: Tensor) -> QuantityTensor: ... - def __rtruediv__(self, other: Quantity | typing.Literal[1]) -> typing.Self | Quantity: - if isinstance(other, Quantity): - return Quantity(other.value, other.unit / self) + def __rtruediv__(self, other: object) -> object: + if isinstance(other, _Quantity): + return _Quantity(other.value, other.unit / self) if isinstance(other, int) and other == 1: return self**-1 return NotImplemented @@ -706,7 +726,7 @@ def coherent_unit(self, dimensionality: Dimension) -> Unit: ) return Unit(UnitComposition(*(UnitOrder(base_unit, order) for base_unit, order in orders), *tagged)) - def coherent_value(self, quantity: Quantity) -> float: + def coherent_value(self, quantity: _Quantity) -> float: """The value of `quantity` in the coherent unit of its dimensionality, or in that unit's absolute counterpart.""" coherent_unit = self.coherent_unit(quantity.unit.dimension) if quantity.unit.category is UnitCategory.ABSOLUTE: diff --git a/tests/api/test_published_linear_systems.py b/tests/api/test_published_linear_systems.py index af549ee3..0b92e097 100644 --- a/tests/api/test_published_linear_systems.py +++ b/tests/api/test_published_linear_systems.py @@ -24,6 +24,7 @@ PYTHON_BACKEND, Implementation, Interface, + Quantity, Tensor, dim, domain, @@ -168,7 +169,7 @@ def _evaluate( else: assert isinstance(value, Tensor) assert value.domain == domain(axis) - assert value.unit is None + assert not isinstance(value, Quantity) values.append(np.asarray(value.values)) return np.stack(values) diff --git a/tests/api/test_reduction_ops.py b/tests/api/test_reduction_ops.py index 4a5aae47..4139990d 100644 --- a/tests/api/test_reduction_ops.py +++ b/tests/api/test_reduction_ops.py @@ -3,12 +3,11 @@ import numpy as np import pytest -from bilt import Implementation, Interface, field, system, transform +from bilt import Implementation, Interface, Tensor, field, system, tensor, transform from bilt._backend._jax._backend import JAX_BACKEND from bilt._backend._python._backend import PYTHON_BACKEND from bilt.core._equation import equation from bilt.core._evaluation_context import EvaluationContext -from bilt.core._tensors._tensors import Tensor, tensor from bilt.symbolic._dimensions import Dim, coordinate_axis from bilt.symbolic._domains import Domain, domain diff --git a/tests/api/test_sub_system.py b/tests/api/test_sub_system.py index 1862506f..c17e83b8 100644 --- a/tests/api/test_sub_system.py +++ b/tests/api/test_sub_system.py @@ -1,14 +1,13 @@ import numpy as np import pytest -from bilt import Implementation, Interface, field, system +from bilt import Implementation, Interface, Tensor, field, system, tensor from bilt._backend._python._backend import PYTHON_BACKEND from bilt.core._equation import equation from bilt.core._evaluation_context import EvaluationContext from bilt.core._evaluation_request import EvaluationRequest from bilt.core._port import DOTTED_SEPARATOR, MANGLED_SEPARATOR, QualifiedPort from bilt.core._sub_system import SubSystemConstituent, validate_name -from bilt.core._tensors._tensors import Tensor, tensor from bilt.errors import BiltAnalysisError, BiltNameError from bilt.symbolic._dimensions import Dim from bilt.symbolic._domains import Domain diff --git a/tests/api/test_system.py b/tests/api/test_system.py index 3f10a513..ae396963 100644 --- a/tests/api/test_system.py +++ b/tests/api/test_system.py @@ -8,6 +8,7 @@ from bilt import ( Implementation, Interface, + Number, Tensor, dim, field, @@ -458,7 +459,7 @@ def test_default_causalization_keeps_supplied_inputs_separate_from_cached_output class Pair(metaclass=Interface): x: float = field() y: float = field() - p: float | Tensor = field() + p: Number = field() q: float = field() @equation @@ -510,7 +511,7 @@ def expose_y(y: float, inner: Pair) -> bool: assert getattr(instance, name) is result -type FlexibleValue = float | Tensor +type FlexibleValue = Number @system @@ -539,4 +540,4 @@ def test_unitless_union_system_field_accepts_scalar_and_tensors() -> None: def test_unitless_union_rejects_unit_bearing_tensor_at_runtime() -> None: with pytest.raises(BiltInputDimensionalityError, match="plain port"): - FlexiblePlainScale(x=tensor([1.0, 2.0], over=dim("time"), unit=kilogram)) + FlexiblePlainScale(x=typing.cast("Tensor", tensor([1.0, 2.0], over=dim("time"), unit=kilogram))) diff --git a/tests/api/test_tensors.py b/tests/api/test_tensors.py index 8f70f831..b6d62701 100644 --- a/tests/api/test_tensors.py +++ b/tests/api/test_tensors.py @@ -4,7 +4,8 @@ import numpy as np import pytest -from bilt.core._tensors._tensors import QuantityTensor, Tensor, tensor +from bilt import Quantity, QuantityTensor, Tensor, tensor +from bilt.core._tensors._tensors import _QuantityTensor, _Tensor from bilt.errors import BiltDimensionalityError, BiltTensorDomainError, BiltUnitError from bilt.symbolic._dimensions import dim from bilt.symbolic._domains import domain @@ -55,7 +56,7 @@ def test_tensor_rejects_incorrect_rank() -> None: BiltTensorDomainError, match="Value rank 2 does not match domain rank 1", ): - Tensor( + _Tensor( values=np.array([[1.0, 2.0]]), domain=domain(time), ) @@ -88,7 +89,7 @@ def test_tensor_arithmetic_is_not_implemented() -> None: def test_a_tensor_has_no_unit_by_default() -> None: - assert tensor([1.0, 2.0], over=dim("time")).unit is None + assert not isinstance(tensor([1.0, 2.0], over=dim("time")), Quantity) def test_a_tensor_takes_a_unit_at_construction() -> None: @@ -178,7 +179,7 @@ def test_tensor_multiplication_outside_the_unit_system_still_raises(operand: obj labelled = tensor([1.0, 2.0], over=dim("time"), unit=gram) with pytest.raises(NotImplementedError, match="Operations will be dispatched through an active backend"): - labelled * operand + labelled * typing.cast("float", operand) def test_negating_a_labelled_tensor_still_raises() -> None: @@ -235,7 +236,7 @@ def test_converting_an_unlabelled_tensor_raises_and_names_the_label() -> None: unlabelled = tensor([1.0, 2.0], over=dim("time")) with pytest.raises(BiltUnitError, match=r"tensor\(\.\.\., unit=\.\.\.\)"): - unlabelled.convert_to(kilogram) + typing.cast("_Tensor", unlabelled).convert_to(kilogram) def test_typed_tensor_factory_and_magnitude_contract() -> None: @@ -244,35 +245,37 @@ def test_typed_tensor_factory_and_magnitude_contract() -> None: typing.assert_type(varied.unit, Unit) typing.assert_type(varied.value, Tensor) assert isinstance(varied, QuantityTensor) - assert varied.value.unit is None + assert not isinstance(varied.value, Quantity) assert varied.value.domain == varied.domain np.testing.assert_array_equal(varied.value.values, varied.values) plain = tensor([1.0, 2.0], over=dim("time")) typing.assert_type(plain, Tensor) - assert type(plain) is Tensor + assert isinstance(plain, Tensor) + assert not isinstance(plain, QuantityTensor) -def _tensor_with_optional_unit(maybe_unit: Unit | None) -> Tensor: +def _tensor_with_optional_unit(maybe_unit: Unit | None) -> Tensor | QuantityTensor: result = tensor([1.0, 2.0], over=dim("time"), unit=maybe_unit) - typing.assert_type(result, Tensor) + typing.assert_type(result, Tensor | QuantityTensor) return result def test_optional_unit_factory_has_conservative_static_return() -> None: assert isinstance(_tensor_with_optional_unit(gram), QuantityTensor) - assert type(_tensor_with_optional_unit(None)) is Tensor + assert not isinstance(_tensor_with_optional_unit(None), QuantityTensor) def test_quantity_tensor_preserves_concrete_type_and_rejects_missing_unit() -> None: labelled = tensor([1000.0, 2000.0], over=dim("time"), unit=gram) converted = labelled.convert_to(kilogram) typing.assert_type(converted, QuantityTensor) - assert type(converted) is QuantityTensor + assert type(converted) is _QuantityTensor - updated = dataclasses.replace(labelled, values=np.asarray([3.0, 4.0])) - assert type(updated) is QuantityTensor + concrete = typing.cast("_QuantityTensor", labelled) + updated = dataclasses.replace(concrete, values=np.asarray([3.0, 4.0])) + assert type(updated) is _QuantityTensor assert updated.unit is gram with pytest.raises(BiltUnitError, match="requires a physical unit"): - dataclasses.replace(labelled, unit=typing.cast("Unit", None)) + dataclasses.replace(concrete, unit=typing.cast("Unit", None)) diff --git a/tests/core/linear/test_broadcast_cross_boundary_blocks.py b/tests/core/linear/test_broadcast_cross_boundary_blocks.py index 35e1e52a..682003a5 100644 --- a/tests/core/linear/test_broadcast_cross_boundary_blocks.py +++ b/tests/core/linear/test_broadcast_cross_boundary_blocks.py @@ -9,6 +9,7 @@ Domain, Implementation, Interface, + Number, Quantity, QuantityTensor, Tensor, @@ -40,7 +41,7 @@ OverTime = typing.Annotated[Tensor, domain(TIME)] Shared = typing.Annotated[Tensor, Domain.scalar()] LengthArray = typing.Annotated[QuantityTensor, LENGTH] -LengthScalar = typing.Annotated[Quantity | QuantityTensor, LENGTH] +LengthScalar = typing.Annotated[Quantity, LENGTH] @system @@ -48,9 +49,9 @@ class Ports(metaclass=Interface): x: Tensor = field() y: Tensor = field() p: Tensor = field() - q: float | Tensor = field() - a: float | Tensor = field() - answer: float | Tensor = field() + q: Number = field() + a: Number = field() + answer: Number = field() @equation @@ -146,7 +147,7 @@ def relation(inner: Lengths, q: LengthScalar) -> bool: result = parent.evaluate( {"inner.p": tensor([0.010, 0.020], over=TIME, unit=kilometer), "q": 2.0 * meter}, output, backend ) - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.unit == meter assert result.domain == domain(TIME) np.testing.assert_allclose(result.values, [6.0, 11.0] if output == "inner.x" else [4.0, 9.0], rtol=1e-5) diff --git a/tests/core/linear/test_broadcast_linear_blocks.py b/tests/core/linear/test_broadcast_linear_blocks.py index 8ab854d0..37607e05 100644 --- a/tests/core/linear/test_broadcast_linear_blocks.py +++ b/tests/core/linear/test_broadcast_linear_blocks.py @@ -6,7 +6,7 @@ import numpy as np import pytest -from bilt import Implementation, Interface, QuantityTensor, Tensor, dim, equation, field, system, tensor +from bilt import Implementation, Interface, Number, QuantityTensor, Tensor, dim, equation, field, system, tensor from bilt._backend._jax._backend import JAX_BACKEND from bilt._backend._python._backend import PYTHON_BACKEND from bilt.core._evaluation_context import EvaluationContext @@ -46,7 +46,7 @@ class Pair(metaclass=Interface): y: Tensor = field() p: Tensor = field() q: float = field() - a: float | Tensor = field() + a: Number = field() def _evaluate( diff --git a/tests/core/linear/test_composed_tensor_equations.py b/tests/core/linear/test_composed_tensor_equations.py index 8b467c8e..8b4c05b1 100644 --- a/tests/core/linear/test_composed_tensor_equations.py +++ b/tests/core/linear/test_composed_tensor_equations.py @@ -31,7 +31,7 @@ TIME = dim("time") BRANCH = dim("branch") LengthArray = typing.Annotated[QuantityTensor, LENGTH] -LengthScalar = typing.Annotated[Quantity | QuantityTensor, LENGTH] +LengthScalar = typing.Annotated[Quantity, LENGTH] MassScalar = typing.Annotated[Quantity, MASS] RatioArray = typing.Annotated[QuantityTensor, DIMENSIONLESS] OverTime = typing.Annotated[Tensor, domain(TIME)] @@ -86,7 +86,7 @@ def weighted(answer: LengthScalar, value: LengthArray, weights: RatioArray) -> b value=tensor(np.arange(1.0, 7.0).reshape(2, 3) / 1000, over=(TIME, BRANCH), unit=kilometer), weights=tensor([1.0, 2.0, 3.0], over=BRANCH, unit=fraction), ).answer - assert isinstance(result, Quantity) + assert not isinstance(result, QuantityTensor) assert result.unit == meter assert float(result.value) == pytest.approx(23.0, abs=1e-5) diff --git a/tests/core/linear/test_coupled_child_subsystems.py b/tests/core/linear/test_coupled_child_subsystems.py index 3b963afe..caee35fb 100644 --- a/tests/core/linear/test_coupled_child_subsystems.py +++ b/tests/core/linear/test_coupled_child_subsystems.py @@ -6,6 +6,7 @@ from bilt import ( Implementation, Interface, + Number, Quantity, QuantityTensor, Tensor, @@ -34,15 +35,15 @@ TIME = dim("time") LengthArray = typing.Annotated[QuantityTensor, LENGTH] -LengthScalar = typing.Annotated[Quantity | QuantityTensor, LENGTH] +LengthScalar = typing.Annotated[Quantity, LENGTH] @system class Pair(metaclass=Interface): - x: float | Tensor = field() - y: float | Tensor = field() - p: float | Tensor = field() - q: float | Tensor = field() + x: Number = field() + y: Number = field() + p: Number = field() + q: Number = field() @equation @@ -155,7 +156,7 @@ def reduction(x: LengthArray, y: LengthScalar, q: LengthScalar) -> bool: backend, ) if output == "x": - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.unit == meter np.testing.assert_allclose(result.values, [0, 2, 4], atol=1e-5) else: diff --git a/tests/core/linear/test_cross_boundary_linear_blocks.py b/tests/core/linear/test_cross_boundary_linear_blocks.py index 83e0b62b..286c2c04 100644 --- a/tests/core/linear/test_cross_boundary_linear_blocks.py +++ b/tests/core/linear/test_cross_boundary_linear_blocks.py @@ -7,8 +7,8 @@ from bilt import ( Implementation, Interface, + Number, Quantity, - QuantityTensor, Tensor, dim, equation, @@ -31,15 +31,15 @@ from bilt._backend import Backend, BackendCallable -Length = typing.Annotated[Quantity | QuantityTensor, LENGTH] +Length = typing.Annotated[Quantity, LENGTH] @system class Pair(metaclass=Interface): - x: float | Tensor = field() - y: float | Tensor = field() - p: float | Tensor = field() - q: float | Tensor = field() + x: Number = field() + y: Number = field() + p: Number = field() + q: Number = field() raw: float = field() answer: float = field() diff --git a/tests/core/linear/test_inferred_linear_blocks.py b/tests/core/linear/test_inferred_linear_blocks.py index 6edd4be8..d3618a3d 100644 --- a/tests/core/linear/test_inferred_linear_blocks.py +++ b/tests/core/linear/test_inferred_linear_blocks.py @@ -7,6 +7,7 @@ Domain, Implementation, Interface, + Number, Quantity, QuantityTensor, Tensor, @@ -34,17 +35,17 @@ OverTime = typing.Annotated[Tensor, domain(TIME)] PerSite = typing.Annotated[Tensor, domain(SITE)] CurrentArray = typing.Annotated[QuantityTensor, CURRENT] -Voltage = typing.Annotated[Quantity | QuantityTensor, VOLTAGE] +Voltage = typing.Annotated[Quantity, VOLTAGE] VoltageArray = typing.Annotated[QuantityTensor, VOLTAGE] -Resistance = typing.Annotated[Quantity | QuantityTensor, RESISTANCE] +Resistance = typing.Annotated[Quantity, RESISTANCE] @system class Pair(metaclass=Interface): x: Tensor = field() y: Tensor = field() - p: float | Tensor = field() - q: float | Tensor = field() + p: Number = field() + q: Number = field() weights: Tensor = field() @@ -207,7 +208,7 @@ def load_balance(current: CurrentArray, bus_voltage: Voltage, load_resistance: R output, ) if output == "current": - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.domain == domain(BRANCH) assert result.unit == ampere np.testing.assert_allclose(result.values, [2.8, 4.8, 6.8], atol=1e-5) diff --git a/tests/core/linear/test_joint_cross_boundary_blocks.py b/tests/core/linear/test_joint_cross_boundary_blocks.py index 38053214..5080a256 100644 --- a/tests/core/linear/test_joint_cross_boundary_blocks.py +++ b/tests/core/linear/test_joint_cross_boundary_blocks.py @@ -10,6 +10,7 @@ Domain, Implementation, Interface, + Number, Quantity, QuantityTensor, Tensor, @@ -46,18 +47,18 @@ PerSite = typing.Annotated[Tensor, domain(SITE)] BranchCurrent = typing.Annotated[QuantityTensor, CURRENT, domain(BRANCH)] SharedVoltage = typing.Annotated[Quantity, VOLTAGE, Domain.scalar()] -SharedVoltageField = typing.Annotated[Quantity, VOLTAGE] +Voltage = typing.Annotated[Quantity, VOLTAGE] VoltageArray = typing.Annotated[QuantityTensor, VOLTAGE] ResistanceArray = typing.Annotated[QuantityTensor, RESISTANCE] -Resistance = typing.Annotated[Quantity | QuantityTensor, RESISTANCE] +Resistance = typing.Annotated[Quantity, RESISTANCE] @system class Ports(metaclass=Interface): x: Tensor = field() - y: float | Tensor = field() + y: Number = field() p: Tensor = field() - q: float | Tensor = field() + q: Number = field() weights: Tensor = field() offset: float = field() @@ -154,7 +155,7 @@ def test_shared_bus_voltage_and_branch_currents_retain_units(backend: Backend, o @system class Bus(metaclass=Interface): current: BranchCurrent = field() - voltage: SharedVoltageField = field() + voltage: Voltage = field() resistance: ResistanceArray = field() load: Resistance = field() @@ -183,7 +184,7 @@ def branch_balance(emf: VoltageArray, inner: Bus) -> bool: backend, ) if output == "inner.current": - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.domain == domain(BRANCH) assert result.unit == ampere np.testing.assert_allclose(result.values, [2.8, 4.8, 6.8], atol=1e-5) diff --git a/tests/core/linear/test_joint_linear_blocks.py b/tests/core/linear/test_joint_linear_blocks.py index 4d29c232..c77ed343 100644 --- a/tests/core/linear/test_joint_linear_blocks.py +++ b/tests/core/linear/test_joint_linear_blocks.py @@ -9,6 +9,7 @@ from bilt import ( Implementation, Interface, + Number, QuantityTensor, Tensor, dim, @@ -47,14 +48,14 @@ LengthArray = typing.Annotated[QuantityTensor, LENGTH] LengthGrid = typing.Annotated[QuantityTensor, LENGTH, domain(TIME)] LengthScalar = typing.Annotated[Quantity, LENGTH, Domain.scalar()] -LengthScalarField = typing.Annotated[Quantity, LENGTH] +Length = typing.Annotated[Quantity, LENGTH] ReverseGrid = typing.Annotated[Tensor, domain(TIME, SITE)] CurrentArray = typing.Annotated[QuantityTensor, CURRENT] BranchCurrent = typing.Annotated[QuantityTensor, CURRENT, domain(BRANCH)] SharedVoltage = typing.Annotated[Quantity, VOLTAGE, Domain.scalar()] -SharedVoltageField = typing.Annotated[Quantity, VOLTAGE] +Voltage = typing.Annotated[Quantity, VOLTAGE] VoltageArray = typing.Annotated[QuantityTensor, VOLTAGE] -Resistance = typing.Annotated[Quantity | QuantityTensor, RESISTANCE] +Resistance = typing.Annotated[Quantity, RESISTANCE] @equation @@ -73,7 +74,7 @@ class Pair(metaclass=Interface): y: Tensor = field() p: Tensor = field() q: float = field() - a: float | Tensor = field() + a: Number = field() def _evaluate( @@ -217,9 +218,9 @@ def test_joint_solve_retains_units_and_distinct_output_domains(backend: Backend, @system class Lengths(metaclass=Interface): x: LengthArray = field() - y: LengthScalarField = field() + y: Length = field() p: LengthArray = field() - q: LengthScalarField = field() + q: Length = field() @equation def first(x: LengthGrid, y: LengthScalar, p: LengthArray) -> bool: @@ -301,7 +302,7 @@ def test_parallel_sources_share_one_bus_voltage(backend: Backend, output: str) - @system class Circuit(metaclass=Interface): current: CurrentArray = field() - bus_voltage: SharedVoltageField = field() + bus_voltage: Voltage = field() source_voltage: VoltageArray = field() branch_resistance: Resistance = field() load_resistance: Resistance = field() @@ -327,7 +328,7 @@ def load_balance(current: BranchCurrent, bus_voltage: SharedVoltage, load_resist ) result = getattr(circuit, output) if output == "current": - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.domain == domain(BRANCH) assert result.unit == ampere np.testing.assert_allclose(result.values, [2.8, 4.8, 6.8], atol=1e-5) diff --git a/tests/core/linear/test_linear_block_execution.py b/tests/core/linear/test_linear_block_execution.py index 19eb8d8c..aa9a3027 100644 --- a/tests/core/linear/test_linear_block_execution.py +++ b/tests/core/linear/test_linear_block_execution.py @@ -26,7 +26,7 @@ from bilt._backend import Backend, BackendCase from bilt.core._model_constituent import BiltModelConstituent -Length = typing.Annotated[Quantity | QuantityTensor, LENGTH] +Length = typing.Annotated[Quantity, LENGTH] @system @@ -281,7 +281,7 @@ def test_quantities_are_solved_in_coherent_units(backend: Backend) -> None: with backend, Implementation(CoupledLengths, [length_total, length_difference]): value = CoupledLengths(p=0.01 * kilometer, q=2.0 * meter).x - assert isinstance(value, Quantity) + assert not isinstance(value, QuantityTensor) assert value.unit == meter assert float(value.value) == pytest.approx(6.0) diff --git a/tests/core/linear/test_linear_block_selections.py b/tests/core/linear/test_linear_block_selections.py index d31340bb..ec240e52 100644 --- a/tests/core/linear/test_linear_block_selections.py +++ b/tests/core/linear/test_linear_block_selections.py @@ -31,7 +31,7 @@ Grid = typing.Annotated[Tensor, domain(TIME, SITE)] LengthArray = typing.Annotated[QuantityTensor, LENGTH] LengthOverTime = typing.Annotated[QuantityTensor, LENGTH, domain(TIME)] -LengthScalar = typing.Annotated[Quantity | QuantityTensor, LENGTH] +LengthScalar = typing.Annotated[Quantity, LENGTH] @equation @@ -151,7 +151,7 @@ def finish(answer: LengthScalar, x: LengthArray) -> bool: assert x.domain == domain(TIME) assert x.unit == meter np.testing.assert_allclose(x.values, [3.6, 5.6, 7.6], atol=1e-5) - assert isinstance(answer, Quantity) + assert not isinstance(answer, QuantityTensor) assert answer.unit == meter assert float(answer.value) == pytest.approx(16.8, abs=1e-5) diff --git a/tests/core/linear/test_linear_operator_broadcast_context.py b/tests/core/linear/test_linear_operator_broadcast_context.py index 6599f02e..aa5455e2 100644 --- a/tests/core/linear/test_linear_operator_broadcast_context.py +++ b/tests/core/linear/test_linear_operator_broadcast_context.py @@ -10,6 +10,7 @@ Domain, Implementation, Interface, + Number, Quantity, QuantityTensor, Tensor, @@ -42,19 +43,18 @@ PerSite = typing.Annotated[Tensor, domain(SITE)] LengthArray = typing.Annotated[QuantityTensor, LENGTH] SharedLength = typing.Annotated[Quantity, LENGTH, Domain.scalar()] -SharedLengthField = typing.Annotated[Quantity, LENGTH] -LengthScalar = typing.Annotated[Quantity | QuantityTensor, LENGTH] +Length = typing.Annotated[Quantity, LENGTH] RatioArray = typing.Annotated[QuantityTensor, DIMENSIONLESS] @system class Pair(metaclass=Interface): - x: float | Tensor = field() - y: float | Tensor = field() - p: float | Tensor = field() - q: float | Tensor = field() + x: Number = field() + y: Number = field() + p: Number = field() + q: Number = field() weights: Tensor = field() - offset: float | Tensor = field() + offset: Number = field() def _balance_for_layout(layout: str) -> BiltModelConstituent: @@ -234,18 +234,18 @@ def test_broadcast_context_preserves_units(backend: Backend, output: str) -> Non @system class Lengths(metaclass=Interface): x: LengthArray = field() - y: SharedLengthField = field() + y: Length = field() p: LengthArray = field() - q: LengthScalar = field() + q: Length = field() weights: RatioArray = field() - offset: LengthScalar = field() + offset: Length = field() @equation def first(x: LengthArray, y: SharedLength, p: LengthArray) -> bool: return x + y == p @equation - def second(x: LengthArray, y: SharedLength, weights: RatioArray, offset: LengthScalar, q: LengthScalar) -> bool: + def second(x: LengthArray, y: SharedLength, weights: RatioArray, offset: Length, q: Length) -> bool: return (weights * x + y + offset).sum(TIME) == q with backend, Implementation(Lengths, [first, second]): diff --git a/tests/core/structural/scc/test_block_realisation_retry.py b/tests/core/structural/scc/test_block_realisation_retry.py index 578c6b22..5f710f59 100644 --- a/tests/core/structural/scc/test_block_realisation_retry.py +++ b/tests/core/structural/scc/test_block_realisation_retry.py @@ -233,8 +233,7 @@ def refuse(function: ast.FunctionDef) -> typing.Never: assert len(candidates) > len(attempts) -type GeneralMass = typing.Annotated[Quantity | QuantityTensor, MASS] -type ScalarMass = typing.Annotated[Quantity, MASS] +type Mass = typing.Annotated[Quantity, MASS] REQ_TIME = dim("required_time") REQ_SCENARIO = dim("scenario") type RequiredTimeMass = typing.Annotated[QuantityTensor, MASS, Domain((REQ_TIME,))] @@ -242,17 +241,17 @@ def refuse(function: ast.FunctionDef) -> typing.Never: @system class MinimumDomainCopy(metaclass=Interface): - x: GeneralMass = field() - y: GeneralMass = field() + x: Mass = field() + y: Mass = field() @equation -def time_limited_copy(x: RequiredTimeMass, y: ScalarMass) -> bool: +def time_limited_copy(x: RequiredTimeMass, y: Mass) -> bool: return y == x @equation -def time_limited_output(x: ScalarMass, y: RequiredTimeMass) -> bool: +def time_limited_output(x: Mass, y: RequiredTimeMass) -> bool: return y == x @@ -275,7 +274,7 @@ def test_equation_minimum_domain_checks_computed_output() -> None: Implementation(MinimumDomainCopy, [time_limited_output]), pytest.raises(BiltExecutionPlanError, match="missing dimensions: required_time") as failure, ): - _ = MinimumDomainCopy(x=Quantity(3.0, kilogram)).y + _ = MinimumDomainCopy(x=3.0 * kilogram).y assert isinstance(failure.value.__cause__, BiltEquationDomainRequirementError) diff --git a/tests/core/tensors/test_lowering_and_lifting.py b/tests/core/tensors/test_lowering_and_lifting.py index 3babefe2..b5a38323 100644 --- a/tests/core/tensors/test_lowering_and_lifting.py +++ b/tests/core/tensors/test_lowering_and_lifting.py @@ -1,12 +1,12 @@ import numpy as np import pytest +from bilt import Tensor, tensor from bilt.core._evaluation_context import EvaluationContext from bilt.core._system._lowering_and_lifting import ( generate_lifting_plan, lift_output, ) -from bilt.core._tensors._tensors import Tensor, tensor from bilt.symbolic._dimensions import Dim from bilt.symbolic._domains import domain diff --git a/tests/core/tensors/test_tensor_broadcasting.py b/tests/core/tensors/test_tensor_broadcasting.py index 206cd2b2..9f4d3b26 100644 --- a/tests/core/tensors/test_tensor_broadcasting.py +++ b/tests/core/tensors/test_tensor_broadcasting.py @@ -3,13 +3,12 @@ import numpy as np import pytest -from bilt import system, transform +from bilt import Tensor, system, tensor, transform from bilt._backend._jax._backend import JAX_BACKEND from bilt._backend._python._backend import PYTHON_BACKEND from bilt.core._interface import Interface from bilt.core._system._field import field from bilt.core._system._implementation import Implementation -from bilt.core._tensors._tensors import Tensor, tensor from bilt.errors import BiltDomainRegistryError from bilt.symbolic._dimensions import Dim from bilt.symbolic._domains import Domain diff --git a/tests/core/tensors/test_transform_lowering.py b/tests/core/tensors/test_transform_lowering.py index e4ead04e..bd37c1c9 100644 --- a/tests/core/tensors/test_transform_lowering.py +++ b/tests/core/tensors/test_transform_lowering.py @@ -21,7 +21,7 @@ if typing.TYPE_CHECKING: import collections.abc - from bilt.core._tensors._tensors import Tensor + from bilt import Tensor def _function_ast( diff --git a/tests/core/test_dimensional_analysis.py b/tests/core/test_dimensional_analysis.py index ebf64a08..a0012e78 100644 --- a/tests/core/test_dimensional_analysis.py +++ b/tests/core/test_dimensional_analysis.py @@ -11,7 +11,6 @@ from bilt.symbolic._dimensions import Dim from bilt.symbolic._expressions import as_tree, symbol_expr, tensor_symbol_expr from bilt.symbolic._tree import Tree, symbol_tree -from bilt.units import Quantity from bilt.units.dimensions import AREA, DIMENSIONLESS, FORCE, LENGTH, MASS, TEMPERATURE, TIME from bilt.units.units import absolute_celsius, kelvin @@ -189,7 +188,7 @@ def test_a_plain_port_and_a_literal_are_read_either_way() -> None: def test_a_quantity_constant_is_absolute_if_its_unit_is() -> None: - assert absoluteness_of("balance", as_tree(Quantity(0.0, absolute_celsius)), {}) == {1} + assert absoluteness_of("balance", as_tree(0.0 * absolute_celsius), {}) == {1} assert absoluteness_of("balance", as_tree(2.0 * kelvin), {}) == {0} diff --git a/tests/core/test_port_declaration.py b/tests/core/test_port_declaration.py index ea571223..95d0e590 100644 --- a/tests/core/test_port_declaration.py +++ b/tests/core/test_port_declaration.py @@ -2,10 +2,9 @@ import pytest -from bilt import Interface, dim, equation, field, system, transform +from bilt import Interface, QuantityTensor, Tensor, dim, equation, field, system, transform from bilt.core._port_declaration import PortDeclaration from bilt.core._structural_analysis._linear_domains import equation_domain_hints -from bilt.core._tensors._tensors import QuantityTensor, Tensor from bilt.errors import BiltEquationDimensionalityError, BiltPortDeclarationError from bilt.symbolic._domains import Domain from bilt.units import Metadata, Quantity, kilogram @@ -20,8 +19,7 @@ Kilograms = typing.Annotated[Quantity, kilogram] MassAsFloat = typing.Annotated[float, MASS] MassAndLength = typing.Annotated[Quantity, MASS, LENGTH] -type MassAlias = typing.Annotated[Quantity, MASS] -type MassAliasAlias = MassAlias +type MassAliasAlias = Mass Temperature = typing.Annotated[Quantity, TEMPERATURE] AbsoluteTemperature = typing.Annotated[Quantity, TEMPERATURE, ABSOLUTE] AbsoluteTime = typing.Annotated[Quantity, TIME, ABSOLUTE] @@ -40,7 +38,7 @@ def test_system_records_only_the_declared_fields() -> None: @system class Rig(metaclass=Interface): plain: float = field() - mass: typing.Annotated[Quantity | QuantityTensor, MASS] = field() + mass: typing.Annotated[Quantity, MASS] = field() assert Rig.__bilt_port_declarations__ == {"mass": PortDeclaration(MASS)} @@ -60,7 +58,7 @@ def balance(m: Mass, length: Length, area: typing.Annotated[Quantity, AREA]) -> def test_equation_records_the_child_dimensionality_of_each_referenced_sub_system_port() -> None: @system class Child(metaclass=Interface): - v: typing.Annotated[Quantity | QuantityTensor, MASS] = field() + v: typing.Annotated[Quantity, MASS] = field() unused: float = field() @equation @@ -112,15 +110,15 @@ def doubled(m: Mass) -> "Mass": def test_type_statement_aliases_are_resolved() -> None: @system class Rig(metaclass=Interface): - mass: MassAlias = field() + mass: Mass = field() nested: MassAliasAlias = field() @equation - def balance(m: MassAlias, n: MassAliasAlias) -> bool: + def balance(m: Mass, n: MassAliasAlias) -> bool: return m == n @transform - def doubled(m: Mass) -> MassAlias: + def doubled(m: Mass) -> Mass: return m * 2.0 assert Rig.__bilt_port_declarations__ == {"mass": PortDeclaration(MASS), "nested": PortDeclaration(MASS)} @@ -140,7 +138,7 @@ class Rig(metaclass=Interface): def test_a_tagged_dimensionality_is_recorded() -> None: @system class Rig(metaclass=Interface): - emitted: typing.Annotated[Quantity | QuantityTensor, MASS * Metadata("co2")] = field() + emitted: typing.Annotated[Quantity, MASS * Metadata("co2")] = field() assert Rig.__bilt_port_declarations__ == {"emitted": PortDeclaration(MASS * Metadata("co2"))} @@ -148,8 +146,8 @@ class Rig(metaclass=Interface): def test_an_absolute_marker_is_recorded_beside_the_dimensionality() -> None: @system class Engine(metaclass=Interface): - hot: typing.Annotated[Quantity | QuantityTensor, TEMPERATURE, ABSOLUTE] = field() - drop: typing.Annotated[Quantity | QuantityTensor, TEMPERATURE] = field() + hot: typing.Annotated[Quantity, TEMPERATURE, ABSOLUTE] = field() + drop: typing.Annotated[Quantity, TEMPERATURE] = field() @equation def cooling(hot: AbsoluteTemperature, cold: AbsoluteTemperature, drop: Temperature) -> bool: @@ -209,7 +207,7 @@ def balance(m: Mass, k: float) -> bool: def test_equation_whose_sub_system_declares_ports_cannot_relate_them_to_a_plain_port() -> None: @system class Child(metaclass=Interface): - v: typing.Annotated[Quantity | QuantityTensor, MASS] = field() + v: typing.Annotated[Quantity, MASS] = field() def link(child: Child, x: float) -> bool: return child.v == x @@ -278,7 +276,7 @@ def test_a_bare_quantity_raises_and_points_both_ways_forward( message = str(raised.value) assert "Annotated[Quantity, DIM]" in message - assert "write `float`" in message + assert "write `Number`" in message def _system_field(annotation: object) -> None: @@ -426,7 +424,7 @@ def test_a_dimensionality_on_a_tensor_is_the_same_declaration_as_on_a_quantity() @system class Rig(metaclass=Interface): over_a_domain: MassOverADomain = field() - scalar: typing.Annotated[Quantity | QuantityTensor, MASS] = field() + scalar: typing.Annotated[Quantity, MASS] = field() assert Rig.__bilt_port_declarations__ == { "over_a_domain": PortDeclaration(MASS), @@ -438,7 +436,7 @@ def test_a_tensor_port_records_that_it_varies_over_a_domain() -> None: @system class Rig(metaclass=Interface): over_a_domain: MassOverADomain = field() - scalar: typing.Annotated[Quantity | QuantityTensor, MASS] = field() + scalar: typing.Annotated[Quantity, MASS] = field() assert Rig.__bilt_port_declarations__["over_a_domain"].over_a_domain assert not Rig.__bilt_port_declarations__["scalar"].over_a_domain @@ -485,19 +483,17 @@ def unchanged(m: MassOverADomain) -> MassOverADomain: assert unchanged.__bilt_port_declarations__ == {"m": PortDeclaration(MASS), "unchanged": PortDeclaration(MASS)} -def test_concrete_quantity_annotation_distinguishes_scalar_and_tensor_ports() -> None: +def test_quantity_takes_any_shape_and_quantity_tensor_requires_a_tensor() -> None: @system class Variants(metaclass=Interface): - flexible: typing.Annotated[Quantity | QuantityTensor, MASS] = field() - scalar: typing.Annotated[Quantity, MASS] = field() + any_shape: typing.Annotated[Quantity, MASS] = field() + old_union: typing.Annotated[Quantity | QuantityTensor, MASS] = field() tensor: typing.Annotated[QuantityTensor, MASS] = field() - concrete: typing.Annotated[QuantityTensor, MASS] = field() declarations = Variants.__bilt_port_declarations__ - assert not declarations["flexible"].scalar_only - assert declarations["scalar"].scalar_only + assert not declarations["any_shape"].over_a_domain + assert not declarations["old_union"].over_a_domain assert declarations["tensor"].over_a_domain - assert declarations["concrete"].over_a_domain assert all(declaration == PortDeclaration(MASS) for declaration in declarations.values()) @@ -506,14 +502,14 @@ def test_bare_pointwise_quantity_still_requires_physical_dimension() -> None: @system class MissingDimension(metaclass=Interface): - mass: Quantity | QuantityTensor = field() + mass: Quantity = field() def test_pointwise_equation_domain_hint_is_exact() -> None: @equation def same( - a: typing.Annotated[Quantity | QuantityTensor, MASS, Domain.scalar()], - b: typing.Annotated[Quantity | QuantityTensor, MASS], + a: typing.Annotated[Quantity, MASS, Domain.scalar()], + b: typing.Annotated[Quantity, MASS], ) -> bool: return a == b @@ -531,7 +527,7 @@ class TensorField(metaclass=Interface): assert TensorField.__bilt_port_declarations__["mass"].required_domain == Domain((time,)) namespace = { - "__annotations__": {"mass": typing.Annotated[Quantity | QuantityTensor, MASS, Domain((time,))]}, + "__annotations__": {"mass": typing.Annotated[Quantity, MASS, Domain((time,))]}, "mass": field(), } with pytest.raises(BiltPortDeclarationError, match="non-tensor quantity"): @@ -542,10 +538,34 @@ class TensorField(metaclass=Interface): def test_dimensioned_tensor_annotation_is_no_longer_supported( declare: collections.abc.Callable[[object], None], ) -> None: - with pytest.raises(BiltPortDeclarationError, match="old dimensioned Tensor annotation"): + with pytest.raises(BiltPortDeclarationError, match="declares a dimensionality on Tensor, which has no unit"): declare(typing.Annotated[Tensor, MASS]) +type _GenericMass[Q] = typing.Annotated[Q, MASS] + + +@pytest.mark.parametrize( + "annotation", + ( + pytest.param(_GenericMass[Quantity], id="subscripted generic alias"), + pytest.param(typing.Annotated[Quantity, MASS] | None, id="inside a union"), + pytest.param(list[typing.Annotated[Quantity, MASS]], id="inside a generic"), + ), +) +@pytest.mark.parametrize(("declare", "owner", "port"), SITES) +def test_a_dimensionality_bilt_cannot_read_raises_instead_of_being_dropped( + declare: collections.abc.Callable[[object], None], + owner: str, + port: str, + annotation: object, +) -> None: + with pytest.raises( + BiltPortDeclarationError, match=f"Port '{port}' of '{owner}' is annotated .*where Bilt cannot read" + ): + declare(annotation) + + def test_scalar_system_field_cannot_require_tensor_domain() -> None: time = dim("time") annotation = typing.Annotated[Quantity, MASS, Domain((time,))] diff --git a/tests/core/test_port_declaration_future_annotations.py b/tests/core/test_port_declaration_future_annotations.py index e76d3e29..70f51712 100644 --- a/tests/core/test_port_declaration_future_annotations.py +++ b/tests/core/test_port_declaration_future_annotations.py @@ -2,24 +2,23 @@ import typing -from bilt import Interface, QuantityTensor, equation, field, system, transform +from bilt import Interface, equation, field, system, transform from bilt.core._port_declaration import PortDeclaration from bilt.units import Quantity from bilt.units.dimensions import MASS Mass = typing.Annotated[Quantity, MASS] -MassField = typing.Annotated[Quantity | QuantityTensor, MASS] @system class Child(metaclass=Interface): - v: MassField = field() + v: Mass = field() def test_system_resolves_annotated_fields() -> None: @system class Rig(metaclass=Interface): - mass: MassField = field() + mass: Mass = field() limit: typing.ClassVar[float] = 1.0 assert Rig.__bilt_port_declarations__ == {"mass": PortDeclaration(MASS)} diff --git a/tests/core/test_tensor_expressions.py b/tests/core/test_tensor_expressions.py index c5b090e4..ca05fc04 100644 --- a/tests/core/test_tensor_expressions.py +++ b/tests/core/test_tensor_expressions.py @@ -2,8 +2,8 @@ import pytest +from bilt import Tensor # noqa: TC001 from bilt.core._equation import equation -from bilt.core._tensors._tensors import Tensor # noqa: TC001 from bilt.symbolic._dimensions import Dim from bilt.symbolic._expressions import Expr, TensorExpr, tensor_symbol_expr from bilt.symbolic._tree import ( diff --git a/tests/dimensionality/test_absolute_quantities.py b/tests/dimensionality/test_absolute_quantities.py index 3c635556..77779232 100644 --- a/tests/dimensionality/test_absolute_quantities.py +++ b/tests/dimensionality/test_absolute_quantities.py @@ -4,7 +4,7 @@ import pytest -from bilt import Implementation, Interface, QuantityTensor, equation, field, system, transform +from bilt import Implementation, Interface, Number, QuantityTensor, equation, field, system, transform from bilt.errors import BiltDefinitionError, BiltEquationDimensionalityError, BiltInputDimensionalityError from bilt.units import Quantity from bilt.units.dimensions import ABSOLUTE, AMOUNT, DIMENSIONLESS, ENERGY, MASS, PRESSURE, TEMPERATURE, TIME, VOLUME @@ -22,17 +22,15 @@ ) AbsoluteTemperature = typing.Annotated[Quantity, TEMPERATURE, ABSOLUTE] -AbsoluteTemperatureField = typing.Annotated[Quantity | QuantityTensor, TEMPERATURE, ABSOLUTE] Temperature = typing.Annotated[Quantity, TEMPERATURE] -TemperatureField = typing.Annotated[Quantity | QuantityTensor, TEMPERATURE] Dimensionless = typing.Annotated[Quantity, DIMENSIONLESS] @system class Heater(metaclass=Interface): - inlet: AbsoluteTemperatureField = field() - rise: TemperatureField = field() - outlet: AbsoluteTemperatureField = field() + inlet: AbsoluteTemperature = field() + rise: Temperature = field() + outlet: AbsoluteTemperature = field() @equation @@ -42,18 +40,18 @@ def heating(outlet: AbsoluteTemperature, inlet: AbsoluteTemperature, rise: Tempe def test_an_absolute_port_counts_from_absolute_zero_and_answers_in_the_absolute_coherent_unit() -> None: with Implementation(Heater, [heating]): - result = Heater(inlet=Quantity(20.0, absolute_celsius), rise=10.0 * celsius).outlet + result = Heater(inlet=20.0 * absolute_celsius, rise=10.0 * celsius).outlet - assert isinstance(result, Quantity) + assert not isinstance(result, QuantityTensor) assert result.unit is absolute_kelvin assert result.value == pytest.approx(303.15) def test_a_relative_port_solved_from_absolute_ports_answers_in_the_relative_coherent_unit() -> None: with Implementation(Heater, [heating]): - result = Heater(inlet=Quantity(20.0, absolute_celsius), outlet=Quantity(86.0, absolute_fahrenheit)).rise + result = Heater(inlet=20.0 * absolute_celsius, outlet=86.0 * absolute_fahrenheit).rise - assert isinstance(result, Quantity) + assert not isinstance(result, QuantityTensor) assert result.unit is kelvin assert result.value == pytest.approx(10.0) @@ -73,7 +71,7 @@ def test_an_absolute_quantity_at_a_relative_port_raises() -> None: with pytest.raises( BiltInputDimensionalityError, match="'rise' of 'Heater' must be a Quantity of temperature" ) as raised: - Heater(inlet=Quantity(20.0, absolute_celsius), rise=Quantity(10.0, absolute_celsius)) + Heater(inlet=20.0 * absolute_celsius, rise=10.0 * absolute_celsius) message = str(raised.value) assert "in a relative unit such as kelvin" in message @@ -90,16 +88,16 @@ def test_a_bare_float_at_an_absolute_port_raises() -> None: def test_an_absolute_unit_whose_dimensionality_cannot_be_absolute_raises() -> None: @system class Clock(metaclass=Interface): - started: typing.Annotated[Quantity | QuantityTensor, TIME] = field() + started: typing.Annotated[Quantity, TIME] = field() with pytest.raises(BiltInputDimensionalityError, match=r"'started' of 'Clock'.*in a relative unit such as second"): - Clock(started=Quantity(2020.0, absolute_year)) + Clock(started=2020.0 * absolute_year) def test_a_compound_unit_containing_an_absolute_unit_raises_at_a_relative_port() -> None: @system class Tank(metaclass=Interface): - thermal_mass: typing.Annotated[Quantity | QuantityTensor, MASS * TEMPERATURE] = field() + thermal_mass: typing.Annotated[Quantity, MASS * TEMPERATURE] = field() with pytest.raises(BiltInputDimensionalityError, match=r"'thermal_mass' of 'Tank'.*in a relative unit") as raised: Tank(thermal_mass=60.0 * kilogram * absolute_celsius) @@ -109,18 +107,18 @@ class Tank(metaclass=Interface): def test_a_compound_unit_containing_an_absolute_unit_raises_at_an_absolute_port() -> None: with pytest.raises(BiltInputDimensionalityError, match=r"'inlet' of 'Heater'.*in an absolute unit"): - Heater(inlet=Quantity(2.0, absolute_celsius**2 / celsius), rise=10.0 * kelvin) + Heater(inlet=2.0 * (absolute_celsius**2 / celsius), rise=10.0 * kelvin) def test_an_absolute_quantity_constant_in_an_equation_counts_from_absolute_zero() -> None: @system class Thermometer(metaclass=Interface): - above_freezing: TemperatureField = field() - reading: AbsoluteTemperatureField = field() + above_freezing: Temperature = field() + reading: AbsoluteTemperature = field() @equation def reading_from_freezing(reading: AbsoluteTemperature, above_freezing: Temperature) -> bool: - return reading == Quantity(0.0, absolute_celsius) + above_freezing + return reading == 0.0 * absolute_celsius + above_freezing with Implementation(Thermometer, [reading_from_freezing]): result = Thermometer(above_freezing=20.0 * kelvin).reading @@ -132,12 +130,12 @@ def reading_from_freezing(reading: AbsoluteTemperature, above_freezing: Temperat def test_an_absolute_quantity_constant_in_a_transform_counts_from_absolute_zero() -> None: @system class Thermometer(metaclass=Interface): - above_freezing: TemperatureField = field() - reading: AbsoluteTemperatureField = field() + above_freezing: Temperature = field() + reading: AbsoluteTemperature = field() @transform def reading(above_freezing: Temperature) -> AbsoluteTemperature: - return Quantity(0.0, absolute_celsius) + above_freezing + return 0.0 * absolute_celsius + above_freezing with Implementation(Thermometer, [reading]): result = Thermometer(above_freezing=20.0 * kelvin).reading @@ -157,16 +155,16 @@ def film_temperature(film: AbsoluteTemperature, hot: AbsoluteTemperature, cold: def test_a_mean_of_absolute_quantities_is_written_from_one_of_them() -> None: @system class Wall(metaclass=Interface): - hot: AbsoluteTemperatureField = field() - cold: AbsoluteTemperatureField = field() - film: AbsoluteTemperatureField = field() + hot: AbsoluteTemperature = field() + cold: AbsoluteTemperature = field() + film: AbsoluteTemperature = field() @equation def film_temperature(film: AbsoluteTemperature, hot: AbsoluteTemperature, cold: AbsoluteTemperature) -> bool: return film == cold + (hot - cold) / 2 with Implementation(Wall, [film_temperature]): - result = Wall(hot=Quantity(40.0, absolute_celsius), cold=Quantity(20.0, absolute_celsius)).film + result = Wall(hot=40.0 * absolute_celsius, cold=20.0 * absolute_celsius).film assert result.unit is absolute_kelvin assert result.value == pytest.approx(303.15) @@ -234,7 +232,7 @@ def thawed(reading: AbsoluteTemperature) -> bool: def test_an_absolute_quantity_constant_relates_to_an_absolute_port() -> None: @equation def thawed(reading: AbsoluteTemperature) -> bool: - return reading > Quantity(0.0, absolute_celsius) + return reading > 0.0 * absolute_celsius def test_a_sub_system_port_keeps_its_absoluteness_in_a_parent_equation() -> None: @@ -248,13 +246,13 @@ def doubled(total: AbsoluteTemperature, heater: Heater) -> bool: @system class Probe(metaclass=Interface): degrees: float = field() - reading: AbsoluteTemperatureField = field() + reading: AbsoluteTemperature = field() -def test_a_constructed_absolute_quantity_brings_a_plain_port_to_an_absolute_one() -> None: +def test_a_plain_number_times_an_absolute_unit_brings_a_plain_port_to_an_absolute_one() -> None: @transform def reading(degrees: float) -> AbsoluteTemperature: - return Quantity(degrees, absolute_fahrenheit) + return degrees * absolute_fahrenheit with Implementation(Probe, [reading]): result = Probe(degrees=68.0).reading @@ -265,11 +263,11 @@ def reading(degrees: float) -> AbsoluteTemperature: def test_a_converted_value_takes_an_absolute_port_out_to_a_plain_one() -> None: @transform - def degrees(reading: AbsoluteTemperature) -> float: + def degrees(reading: AbsoluteTemperature) -> Number: return reading.convert_to(absolute_fahrenheit).value with Implementation(Probe, [degrees]): - assert Probe(reading=Quantity(20.0, absolute_celsius)).degrees == pytest.approx(68.0) + assert Probe(reading=20.0 * absolute_celsius).degrees == pytest.approx(68.0) def test_a_conversion_to_an_absolute_unit_answers_the_same_quantity() -> None: @@ -278,7 +276,7 @@ def outlet(inlet: AbsoluteTemperature) -> AbsoluteTemperature: return inlet.convert_to(absolute_celsius) with Implementation(Heater, [outlet]): - result = Heater(inlet=Quantity(20.0, absolute_celsius)).outlet + result = Heater(inlet=20.0 * absolute_celsius).outlet assert result.unit is absolute_kelvin assert result.value == pytest.approx(293.15) @@ -287,10 +285,10 @@ def outlet(inlet: AbsoluteTemperature) -> AbsoluteTemperature: def test_a_body_working_in_degrees_means_what_python_means() -> None: @transform def outlet(inlet: AbsoluteTemperature) -> AbsoluteTemperature: - return Quantity(inlet.convert_to(absolute_celsius).value + 10.0, absolute_celsius) + return (inlet.convert_to(absolute_celsius).value + 10.0) * absolute_celsius with Implementation(Heater, [outlet]): - result = Heater(inlet=Quantity(68.0, absolute_fahrenheit)).outlet + result = Heater(inlet=68.0 * absolute_fahrenheit).outlet assert result.unit is absolute_kelvin assert result.value == pytest.approx(303.15) @@ -304,7 +302,7 @@ def test_converting_an_absolute_parameter_to_a_relative_unit_is_refused() -> Non ): @transform - def degrees(inlet: AbsoluteTemperature) -> float: + def degrees(inlet: AbsoluteTemperature) -> Number: return inlet.convert_to(celsius).value @@ -322,28 +320,28 @@ def outlet(rise: Temperature) -> AbsoluteTemperature: def test_a_conversion_of_anything_deeper_than_a_parameter_is_taken_at_its_word() -> None: @transform - def degrees(reading: AbsoluteTemperature) -> float: - return (reading - Quantity(0.0, absolute_celsius)).convert_to(fahrenheit).value + def degrees(reading: AbsoluteTemperature) -> Number: + return (reading - 0.0 * absolute_celsius).convert_to(fahrenheit).value with Implementation(Probe, [degrees]): - assert Probe(reading=Quantity(10.0, absolute_celsius)).degrees == pytest.approx(18.0) + assert Probe(reading=10.0 * absolute_celsius).degrees == pytest.approx(18.0) def test_a_conversion_of_a_reassigned_parameter_is_taken_at_its_word() -> None: @transform - def degrees(reading: AbsoluteTemperature) -> float: - reading = reading - Quantity(0.0, absolute_celsius) + def degrees(reading: AbsoluteTemperature) -> Number: + reading = reading - 0.0 * absolute_celsius return reading.convert_to(fahrenheit).value with Implementation(Probe, [degrees]): - assert Probe(reading=Quantity(10.0, absolute_celsius)).degrees == pytest.approx(18.0) + assert Probe(reading=10.0 * absolute_celsius).degrees == pytest.approx(18.0) def test_a_comprehension_variable_named_as_a_parameter_does_not_reassign_it() -> None: with pytest.raises(BiltDefinitionError, match=r"`reading\.convert_to\(celsius\)` contradicts the signature"): @transform - def degrees(reading: AbsoluteTemperature) -> float: + def degrees(reading: AbsoluteTemperature) -> Number: doubled = [reading * 2.0 for reading in [1.0, 2.0]] return reading.convert_to(celsius).value + doubled[0] @@ -352,7 +350,7 @@ def test_a_conversion_in_the_iterable_of_a_comprehension_reads_the_parameter() - with pytest.raises(BiltDefinitionError, match=r"`reading\.convert_to\(celsius\)` contradicts the signature"): @transform - def degrees(reading: AbsoluteTemperature) -> float: + def degrees(reading: AbsoluteTemperature) -> Number: values = [reading for reading in [reading.convert_to(celsius).value] if reading > 0.0] return values[0] @@ -361,8 +359,8 @@ def test_a_conversion_in_a_parameter_default_reads_the_parameter() -> None: with pytest.raises(BiltDefinitionError, match=r"`reading\.convert_to\(celsius\)` contradicts the signature"): @transform - def degrees(reading: AbsoluteTemperature) -> float: - def scaled(reading: float = reading.convert_to(celsius).value) -> float: + def degrees(reading: AbsoluteTemperature) -> Number: + def scaled(reading: Number = reading.convert_to(celsius).value) -> Number: # noqa: B008 return reading return scaled() @@ -372,7 +370,7 @@ def test_a_conversion_in_the_iterable_of_a_nested_comprehension_reads_the_parame with pytest.raises(BiltDefinitionError, match=r"`reading\.convert_to\(celsius\)` contradicts the signature"): @transform - def degrees(reading: AbsoluteTemperature) -> float: + def degrees(reading: AbsoluteTemperature) -> Number: rows = [[reading for reading in [reading.convert_to(celsius).value] if reading > 0.0] for _ in [1.0]] return rows[0][0] @@ -381,28 +379,28 @@ def test_a_binding_deeper_in_a_comprehension_does_not_shadow_the_parameter() -> with pytest.raises(BiltDefinitionError, match=r"`reading\.convert_to\(celsius\)` contradicts the signature"): @transform - def degrees(reading: AbsoluteTemperature) -> float: + def degrees(reading: AbsoluteTemperature) -> Number: values = [reading.convert_to(celsius).value + sum(reading for reading in [1.0]) for _ in [1.0]] return values[0] def test_a_coherent_conversion_in_the_iterable_of_a_comprehension_is_still_erased() -> None: @transform - def degrees(reading: AbsoluteTemperature) -> float: + def degrees(reading: AbsoluteTemperature) -> Number: values = [reading for reading in [reading.convert_to(absolute_fahrenheit).value] if reading > 0.0] return values[0] with Implementation(Probe, [degrees]): - assert Probe(reading=Quantity(10.0, absolute_celsius)).degrees == pytest.approx(50.0) + assert Probe(reading=10.0 * absolute_celsius).degrees == pytest.approx(50.0) def test_an_absolute_unit_with_no_coherent_counterpart_is_refused_in_a_transform() -> None: with pytest.raises( BiltDefinitionError, - match=r"`absolute_year` cannot be converted to a coherent unit, so `Quantity\(elapsed, absolute_year\)` " + match=r"`absolute_year` cannot be converted to a coherent unit, so `elapsed \* absolute_year` " r"cannot use it", ): @transform def started(elapsed: float) -> typing.Annotated[Quantity, TIME]: - return Quantity(elapsed, absolute_year) + return elapsed * absolute_year diff --git a/tests/dimensionality/test_constructed_plain_objects.py b/tests/dimensionality/test_constructed_plain_objects.py index 0bf44fad..4579a3b7 100644 --- a/tests/dimensionality/test_constructed_plain_objects.py +++ b/tests/dimensionality/test_constructed_plain_objects.py @@ -4,9 +4,10 @@ import pytest -from bilt import transform +from bilt import Number, transform from bilt.errors import BiltDefinitionError -from bilt.units import Quantity, meter +from bilt.units import meter +from bilt.units._quantities import _Quantity def test_unit_erasure_preserves_value_on_a_constructed_plain_object() -> None: @@ -36,9 +37,9 @@ def test_reassignment_does_not_mark_a_quantity_as_plain() -> None: with pytest.raises(BiltDefinitionError, match=r"record\.value"): @transform - def extracted(value: float) -> float: + def extracted(value: float) -> Number: record: object = SimpleNamespace(value=value) - record = Quantity(value, meter) + record = value * meter return record.value @@ -47,7 +48,7 @@ def test_a_shadowed_constructor_does_not_mark_a_quantity_as_plain() -> None: @transform def extracted(value: float) -> float: - namespace: type[SimpleNamespace | Quantity] = SimpleNamespace - namespace = Quantity + namespace: type[SimpleNamespace | _Quantity] = SimpleNamespace + namespace = _Quantity record = namespace(value, meter) return record.value diff --git a/tests/dimensionality/test_cross_constituent.py b/tests/dimensionality/test_cross_constituent.py index 163b7dd6..1a5f82c5 100644 --- a/tests/dimensionality/test_cross_constituent.py +++ b/tests/dimensionality/test_cross_constituent.py @@ -4,22 +4,17 @@ import pytest -from bilt import Implementation, Interface, QuantityTensor, equation, field, system, transform +from bilt import Implementation, Interface, equation, field, system, transform from bilt.errors import BiltImplementationDimensionalityError, BiltUnitsError from bilt.units import Quantity from bilt.units.dimensions import ABSOLUTE, CURRENT, FORCE, MASS, POWER, RESISTANCE, TEMPERATURE, VOLTAGE Current = typing.Annotated[Quantity, CURRENT] -CurrentField = typing.Annotated[Quantity | QuantityTensor, CURRENT] Force = typing.Annotated[Quantity, FORCE] -ForceField = typing.Annotated[Quantity | QuantityTensor, FORCE] Mass = typing.Annotated[Quantity, MASS] -MassField = typing.Annotated[Quantity | QuantityTensor, MASS] Power = typing.Annotated[Quantity, POWER] Resistance = typing.Annotated[Quantity, RESISTANCE] -ResistanceField = typing.Annotated[Quantity | QuantityTensor, RESISTANCE] Voltage = typing.Annotated[Quantity, VOLTAGE] -VoltageField = typing.Annotated[Quantity | QuantityTensor, VOLTAGE] @equation @@ -40,10 +35,10 @@ def halving(halved: Voltage, scaled: Voltage) -> bool: def test_constituents_agreeing_on_a_shared_port_construct() -> None: @system class Rig(metaclass=Interface): - v: VoltageField = field() - i: CurrentField = field() - r: ResistanceField = field() - scaled: VoltageField = field() + v: Voltage = field() + i: Current = field() + r: Resistance = field() + scaled: Voltage = field() Implementation(Rig, [ohms_law, doubling]) @@ -51,10 +46,10 @@ class Rig(metaclass=Interface): def test_a_port_only_one_constituent_declares_raises_naming_the_declaring_owner_and_the_plain_one() -> None: @system class Rig(metaclass=Interface): - v: VoltageField = field() - i: CurrentField = field() - r: ResistanceField = field() - scaled: VoltageField = field() + v: Voltage = field() + i: Current = field() + r: Resistance = field() + scaled: Voltage = field() @equation def plain_doubling(scaled: float, v: float) -> bool: @@ -73,9 +68,9 @@ def plain_doubling(scaled: float, v: float) -> bool: def test_a_declared_conflict_names_both_sources() -> None: @system class Rig(metaclass=Interface): - v: VoltageField = field() - i: CurrentField = field() - r: ResistanceField = field() + v: Voltage = field() + i: Current = field() + r: Resistance = field() @equation def resting(v: Mass) -> bool: @@ -92,11 +87,11 @@ def resting(v: Mass) -> bool: def test_a_conflict_reads_the_same_whatever_the_constituent_order() -> None: @system class Rig(metaclass=Interface): - v: VoltageField = field() - i: CurrentField = field() - r: ResistanceField = field() - scaled: ForceField = field() - halved: VoltageField = field() + v: Voltage = field() + i: Current = field() + r: Resistance = field() + scaled: Force = field() + halved: Voltage = field() messages = set() for constituents in ([ohms_law, doubling, halving], [halving, doubling, ohms_law]): @@ -110,9 +105,9 @@ class Rig(metaclass=Interface): def test_a_sub_system_holds_its_ports_to_their_declarations_under_their_dotted_names() -> None: @system class Resistor(metaclass=Interface): - v: VoltageField = field() - i: CurrentField = field() - r: ResistanceField = field() + v: Voltage = field() + i: Current = field() + r: Resistance = field() with pytest.raises(BiltUnitsError, match="wiring") as raised: @@ -128,9 +123,9 @@ def wiring(out: Mass, resistor: Resistor) -> bool: def test_a_transform_output_takes_its_return_annotation() -> None: @system class Rig(metaclass=Interface): - v: VoltageField = field() - i: CurrentField = field() - power: MassField = field() + v: Voltage = field() + i: Current = field() + power: Mass = field() @transform def power(v: Voltage, i: Current) -> Power: @@ -147,7 +142,7 @@ def power(v: Voltage, i: Current) -> Power: def test_a_port_one_owner_marks_absolute_and_another_leaves_relative_raises() -> None: @system class Engine(metaclass=Interface): - hot: typing.Annotated[Quantity | QuantityTensor, TEMPERATURE, ABSOLUTE] = field() + hot: typing.Annotated[Quantity, TEMPERATURE, ABSOLUTE] = field() @equation def resting(hot: typing.Annotated[Quantity, TEMPERATURE]) -> bool: diff --git a/tests/dimensionality/test_declared_or_plain.py b/tests/dimensionality/test_declared_or_plain.py index e176b1db..3bafb15e 100644 --- a/tests/dimensionality/test_declared_or_plain.py +++ b/tests/dimensionality/test_declared_or_plain.py @@ -4,7 +4,7 @@ import pytest -from bilt import Implementation, Interface, QuantityTensor, Tensor, equation, field, system, transform +from bilt import Implementation, Interface, Tensor, equation, field, system, transform from bilt.errors import ( BiltEquationDimensionalityError, BiltImplementationDimensionalityError, @@ -14,19 +14,15 @@ from bilt.units.units import volt Dimensionless = typing.Annotated[Quantity, DIMENSIONLESS] -DimensionlessField = typing.Annotated[Quantity | QuantityTensor, DIMENSIONLESS] Length = typing.Annotated[Quantity, LENGTH] -LengthField = typing.Annotated[Quantity | QuantityTensor, LENGTH] Mass = typing.Annotated[Quantity, MASS] -MassField = typing.Annotated[Quantity | QuantityTensor, MASS] Voltage = typing.Annotated[Quantity, VOLTAGE] -VoltageField = typing.Annotated[Quantity | QuantityTensor, VOLTAGE] def test_a_system_interface_may_mix_declared_and_plain_ports() -> None: @system class Rig(metaclass=Interface): - m: MassField = field() + m: Mass = field() count: float = field() @equation @@ -43,8 +39,8 @@ def counting(count: float) -> bool: def test_a_port_the_interface_declares_and_a_constituent_leaves_plain_raises() -> None: @system class Rig(metaclass=Interface): - x: LengthField = field() - y: LengthField = field() + x: Length = field() + y: Length = field() @equation def doubling(y: float, x: float) -> bool: @@ -80,7 +76,7 @@ def test_a_transform_without_a_return_annotation_does_not_declare_its_output() - @system class Rig(metaclass=Interface): x: float = field() - half: MassField = field() + half: Mass = field() @transform def half(x: float): # noqa: ANN202 @@ -93,7 +89,7 @@ def half(x: float): # noqa: ANN202 def test_an_intermediate_port_declared_by_one_constituent_and_plain_in_another_raises() -> None: @system class Rig(metaclass=Interface): - x: MassField = field() + x: Mass = field() @equation def declared_link(x: Mass, middle: Mass) -> bool: @@ -116,7 +112,7 @@ def plain_link(middle: float, other: float) -> bool: def test_a_plain_port_answers_with_a_bare_number_however_many_declared_ports_exist_elsewhere() -> None: @system class Rig(metaclass=Interface): - v: VoltageField = field() + v: Voltage = field() x: float = field() scaled: float = field() @@ -146,39 +142,39 @@ def scaling(m: Mass, scales: Tensor) -> bool: def test_a_transform_with_a_plain_flag_beside_declared_ports_evaluates_by_the_flag() -> None: @system class Combiner(metaclass=Interface): - a: DimensionlessField = field() - b: DimensionlessField = field() + a: Dimensionless = field() + b: Dimensionless = field() add: bool = field() - combined: DimensionlessField = field() + combined: Dimensionless = field() @transform def combined(a: Dimensionless, b: Dimensionless, add: bool) -> Dimensionless: return a + b if add else a * b - two, three = Quantity(2.0, UNITLESS), Quantity(3.0, UNITLESS) + two, three = 2.0 * UNITLESS, 3.0 * UNITLESS with Implementation(Combiner, [combined]): added = Combiner(a=two, b=three, add=True).combined multiplied = Combiner(a=two, b=three, add=False).combined - assert added == Quantity(5.0, UNITLESS) - assert multiplied == Quantity(6.0, UNITLESS) + assert added == 5.0 * UNITLESS + assert multiplied == 6.0 * UNITLESS def test_an_equation_with_a_plain_exponent_beside_declared_ports_evaluates() -> None: @system class Power(metaclass=Interface): - x: DimensionlessField = field() + x: Dimensionless = field() n: float = field() - y: DimensionlessField = field() + y: Dimensionless = field() @equation def powered(y: Dimensionless, x: Dimensionless, n: float) -> bool: return y == x**n with Implementation(Power, [powered]): - result = Power(x=Quantity(3.0, UNITLESS), n=2.0).y + result = Power(x=3.0 * UNITLESS, n=2.0).y - assert result == Quantity(9.0, UNITLESS) + assert result == 9.0 * UNITLESS def test_a_plain_port_meeting_a_declared_port_inside_an_exponent_raises() -> None: @@ -192,9 +188,9 @@ def scaled_power(y: Dimensionless, x: Dimensionless, length: Length, scale: floa def test_a_plain_transform_port_that_another_owner_declares_raises() -> None: @system class Rig(metaclass=Interface): - a: DimensionlessField = field() - scale: DimensionlessField = field() - scaled: DimensionlessField = field() + a: Dimensionless = field() + scale: Dimensionless = field() + scaled: Dimensionless = field() @transform def scaled(a: Dimensionless, scale: float) -> Dimensionless: @@ -206,9 +202,9 @@ def scaled(a: Dimensionless, scale: float) -> Dimensionless: @system class Amplifier(metaclass=Interface): - gain: DimensionlessField = field() - x: LengthField = field() - amplified: LengthField = field() + gain: Dimensionless = field() + x: Length = field() + amplified: Length = field() @equation diff --git a/tests/dimensionality/test_declared_tensors_in_equations.py b/tests/dimensionality/test_declared_tensors_in_equations.py index df9d725b..2e91452e 100644 --- a/tests/dimensionality/test_declared_tensors_in_equations.py +++ b/tests/dimensionality/test_declared_tensors_in_equations.py @@ -23,31 +23,25 @@ from bilt.units.dimensions import ABSOLUTE, DIMENSIONLESS, FORCE, MASS, TEMPERATURE Mass = typing.Annotated[Quantity, MASS] -MassField = typing.Annotated[Quantity | QuantityTensor, MASS] MassOverADomain = typing.Annotated[QuantityTensor, MASS] -MassOverADomainField = typing.Annotated[QuantityTensor, MASS] Force = typing.Annotated[Quantity, FORCE] Ratio = typing.Annotated[Quantity, DIMENSIONLESS] -RatioField = typing.Annotated[Quantity | QuantityTensor, DIMENSIONLESS] RatioOverADomain = typing.Annotated[QuantityTensor, DIMENSIONLESS] -RatioOverADomainField = typing.Annotated[QuantityTensor, DIMENSIONLESS] AbsoluteTemperature = typing.Annotated[Quantity, TEMPERATURE, ABSOLUTE] -AbsoluteTemperatureField = typing.Annotated[Quantity | QuantityTensor, TEMPERATURE, ABSOLUTE] AbsoluteTemperatureOverADomain = typing.Annotated[QuantityTensor, TEMPERATURE, ABSOLUTE] -AbsoluteTemperatureOverADomainField = typing.Annotated[QuantityTensor, TEMPERATURE, ABSOLUTE] time = dim("time") @system class Scale(metaclass=Interface): - m: MassOverADomainField = field() - reduced: MassField = field() + m: MassOverADomain = field() + reduced: Mass = field() @system class Thermometer(metaclass=Interface): - t: AbsoluteTemperatureOverADomainField = field() - reduced: AbsoluteTemperatureField = field() + t: AbsoluteTemperatureOverADomain = field() + reduced: AbsoluteTemperature = field() @pytest.mark.parametrize( @@ -116,8 +110,8 @@ def product(reduced: Mass, m: MassOverADomain) -> bool: def test_a_product_along_an_axis_of_a_dimensionless_port_is_dimensionless() -> None: @system class Ratios(metaclass=Interface): - ratios: RatioOverADomainField = field() - combined: RatioField = field() + ratios: RatioOverADomain = field() + combined: Ratio = field() @equation def combining(combined: Ratio, ratios: RatioOverADomain) -> bool: @@ -126,7 +120,7 @@ def combining(combined: Ratio, ratios: RatioOverADomain) -> bool: with Implementation(Ratios, [combining]): result = Ratios(ratios=tensor([2.0, 3.0], over=time, unit=fraction)).combined - assert result == Quantity(6.0, fraction) + assert result == 6.0 * fraction def test_a_product_along_an_axis_of_a_dimensionless_port_against_a_dimensional_one_raises() -> None: @@ -153,7 +147,7 @@ def first(reduced: AbsoluteTemperature, t: AbsoluteTemperatureOverADomain) -> bo with Implementation(Thermometer, [first]): result = Thermometer(t=tensor([273.15, 373.15], over=time, unit=abs(kelvin))).reduced - assert result == Quantity(273.15, abs(kelvin)) + assert result == 273.15 * abs(kelvin) def test_a_selection_of_an_absolute_port_related_to_a_relative_one_raises() -> None: diff --git a/tests/dimensionality/test_direct_evaluate_input_validation.py b/tests/dimensionality/test_direct_evaluate_input_validation.py index e492ab22..b42d099e 100644 --- a/tests/dimensionality/test_direct_evaluate_input_validation.py +++ b/tests/dimensionality/test_direct_evaluate_input_validation.py @@ -19,24 +19,18 @@ from bilt.units.dimensions import ABSOLUTE, CURRENT, LENGTH, RESISTANCE, TEMPERATURE, VOLTAGE Current = typing.Annotated[Quantity, CURRENT] -CurrentField = typing.Annotated[Quantity | QuantityTensor, CURRENT] Resistance = typing.Annotated[Quantity, RESISTANCE] -ResistanceField = typing.Annotated[Quantity | QuantityTensor, RESISTANCE] Voltage = typing.Annotated[Quantity, VOLTAGE] -VoltageField = typing.Annotated[Quantity | QuantityTensor, VOLTAGE] Length = typing.Annotated[Quantity, LENGTH] -LengthField = typing.Annotated[Quantity | QuantityTensor, LENGTH] LengthSeries = typing.Annotated[QuantityTensor, LENGTH] -LengthSeriesField = typing.Annotated[QuantityTensor, LENGTH] AbsoluteTemperature = typing.Annotated[Quantity, TEMPERATURE, ABSOLUTE] -AbsoluteTemperatureField = typing.Annotated[Quantity | QuantityTensor, TEMPERATURE, ABSOLUTE] @system class Resistor(metaclass=Interface): - i: CurrentField = field() - r: ResistanceField = field() - v: VoltageField = field() + i: Current = field() + r: Resistance = field() + v: Voltage = field() @equation @@ -71,7 +65,7 @@ def test_direct_evaluate_validates_before_returning_an_existing_output() -> None @system class TemperatureProbe(metaclass=Interface): - reading: AbsoluteTemperatureField = field() + reading: AbsoluteTemperature = field() def test_direct_evaluate_rejects_a_relative_temperature_at_an_absolute_port() -> None: @@ -83,7 +77,7 @@ def test_direct_evaluate_rejects_a_relative_temperature_at_an_absolute_port() -> def test_direct_evaluate_accepts_an_absolute_temperature() -> None: model = Implementation(TemperatureProbe, []) - reading = Quantity(20.0, absolute_celsius) + reading = 20.0 * absolute_celsius assert model.evaluate({"reading": reading}, "reading", PYTHON_BACKEND) is reading @@ -102,8 +96,8 @@ def test_direct_evaluate_rejects_a_quantity_at_a_plain_port() -> None: @system class Stretch(metaclass=Interface): - x: LengthField = field() - y: LengthField = field() + x: Length = field() + y: Length = field() @transform @@ -137,8 +131,8 @@ def test_direct_evaluate_lifts_a_declared_intermediate_output() -> None: @system class TensorStretch(metaclass=Interface): - x: LengthSeriesField = field() - y: LengthSeriesField = field() + x: LengthSeries = field() + y: LengthSeries = field() @equation diff --git a/tests/dimensionality/test_input_validation.py b/tests/dimensionality/test_input_validation.py index 6ddb1e35..69190268 100644 --- a/tests/dimensionality/test_input_validation.py +++ b/tests/dimensionality/test_input_validation.py @@ -11,30 +11,21 @@ from bilt.units.units import absolute_celsius, ampere, kelvin, kilogram, kilometer, meter, ohm Current = typing.Annotated[Quantity, CURRENT] -CurrentField = typing.Annotated[Quantity | QuantityTensor, CURRENT] Dimensionless = typing.Annotated[Quantity, DIMENSIONLESS] -DimensionlessField = typing.Annotated[Quantity | QuantityTensor, DIMENSIONLESS] Length = typing.Annotated[Quantity, LENGTH] -LengthField = typing.Annotated[Quantity | QuantityTensor, LENGTH] Mass = typing.Annotated[Quantity, MASS] -MassField = typing.Annotated[Quantity | QuantityTensor, MASS] Resistance = typing.Annotated[Quantity, RESISTANCE] -ResistanceField = typing.Annotated[Quantity | QuantityTensor, RESISTANCE] Temperature = typing.Annotated[Quantity, TEMPERATURE] -TemperatureField = typing.Annotated[Quantity | QuantityTensor, TEMPERATURE] AbsoluteTemperature = typing.Annotated[Quantity, TEMPERATURE, ABSOLUTE] -AbsoluteTemperatureField = typing.Annotated[Quantity | QuantityTensor, TEMPERATURE, ABSOLUTE] MassOverADomain = typing.Annotated[QuantityTensor, MASS] -MassOverADomainField = typing.Annotated[QuantityTensor, MASS] Voltage = typing.Annotated[Quantity, VOLTAGE] -VoltageField = typing.Annotated[Quantity | QuantityTensor, VOLTAGE] @system class Resistor(metaclass=Interface): - v: VoltageField = field() - i: CurrentField = field() - r: ResistanceField = field() + v: Voltage = field() + i: Current = field() + r: Resistance = field() @equation @@ -44,9 +35,9 @@ def ohms_law(v: Voltage, i: Current, r: Resistance) -> bool: @system class Amplifier(metaclass=Interface): - gain: DimensionlessField = field() - x: LengthField = field() - amplified: LengthField = field() + gain: Dimensionless = field() + x: Length = field() + amplified: Length = field() @equation @@ -56,14 +47,14 @@ def amplifying(amplified: Length, gain: Dimensionless, x: Length) -> bool: @system class MassScale(metaclass=Interface): - m: MassField = field() - doubled: MassField = field() + m: Mass = field() + doubled: Mass = field() @system class TensorScale(metaclass=Interface): - m: MassOverADomainField = field() - doubled: MassField = field() + m: MassOverADomain = field() + doubled: Mass = field() @system @@ -74,14 +65,14 @@ class PlainScale(metaclass=Interface): @system class Thermometer(metaclass=Interface): - t: TemperatureField = field() - same: TemperatureField = field() + t: Temperature = field() + same: Temperature = field() @system class AbsoluteThermometer(metaclass=Interface): - t: AbsoluteTemperatureField = field() - same: AbsoluteTemperatureField = field() + t: AbsoluteTemperature = field() + same: AbsoluteTemperature = field() def test_a_bare_float_at_an_annotated_port_raises() -> None: @@ -104,7 +95,7 @@ def test_a_quantity_of_the_declared_dimensionality_evaluates() -> None: with Implementation(Resistor, [ohms_law]): result = Resistor(i=2.0 * ampere, r=3.0 * ohm).v - assert isinstance(result, Quantity) + assert not isinstance(result, QuantityTensor) assert result.value == pytest.approx(6.0) assert result.unit.dimension == VOLTAGE @@ -116,14 +107,14 @@ def test_a_dimensionless_port_rejects_a_bare_float() -> None: def test_a_dimensionless_port_accepts_a_dimensionless_quantity() -> None: with Implementation(Amplifier, [amplifying]): - result = Amplifier(gain=Quantity(2.0, UNITLESS), x=3.0 * meter).amplified + result = Amplifier(gain=2.0 * UNITLESS, x=3.0 * meter).amplified assert result == 6.0 * meter def test_a_declared_port_accepts_a_quantity_in_any_unit_of_its_dimensionality() -> None: with Implementation(Amplifier, [amplifying]): - result = Amplifier(gain=Quantity(2.0, UNITLESS), x=3.0 * kilometer).amplified + result = Amplifier(gain=2.0 * UNITLESS, x=3.0 * kilometer).amplified assert result == 6000.0 * meter @@ -164,7 +155,7 @@ def test_a_relative_tensor_at_an_absolute_port_raises() -> None: def test_a_unit_carrying_tensor_at_a_plain_port_raises() -> None: masses = tensor([1.0, 2.0], over=dim("time"), unit=kilogram) with pytest.raises(BiltInputDimensionalityError, match="'x'") as raised: - PlainScale(x=masses) + PlainScale(x=typing.cast("Tensor", masses)) message = str(raised.value) assert "plain port" in message @@ -183,8 +174,8 @@ def test_a_scalar_quantity_at_a_tensor_annotated_port_raises() -> None: def test_a_quantity_of_the_wrong_dimensionality_at_a_port_only_a_constituent_reads_raises() -> None: @system class Rig(metaclass=Interface): - v: VoltageField = field() - scaled: VoltageField = field() + v: Voltage = field() + scaled: Voltage = field() @equation def doubling(scaled: Voltage, v: Voltage) -> bool: diff --git a/tests/dimensionality/test_quantity_constants_in_equations.py b/tests/dimensionality/test_quantity_constants_in_equations.py index 66db5b5f..06529c10 100644 --- a/tests/dimensionality/test_quantity_constants_in_equations.py +++ b/tests/dimensionality/test_quantity_constants_in_equations.py @@ -4,29 +4,24 @@ import pytest -from bilt import Implementation, Interface, QuantityTensor, equation, field, system +from bilt import Implementation, Interface, equation, field, system from bilt.errors import BiltEquationDimensionalityError, BiltSymbolicConversionError from bilt.units import UNITLESS, Quantity from bilt.units.dimensions import DIMENSIONLESS, FORCE, LENGTH, MASS, TEMPERATURE, TIME from bilt.units.units import absolute_celsius, hour, kilogram, kilometer, meter, newton, second Dimensionless = typing.Annotated[Quantity, DIMENSIONLESS] -DimensionlessField = typing.Annotated[Quantity | QuantityTensor, DIMENSIONLESS] Force = typing.Annotated[Quantity, FORCE] -ForceField = typing.Annotated[Quantity | QuantityTensor, FORCE] Length = typing.Annotated[Quantity, LENGTH] -LengthField = typing.Annotated[Quantity | QuantityTensor, LENGTH] Mass = typing.Annotated[Quantity, MASS] -MassField = typing.Annotated[Quantity | QuantityTensor, MASS] Temperature = typing.Annotated[Quantity, TEMPERATURE] Time = typing.Annotated[Quantity, TIME] -TimeField = typing.Annotated[Quantity | QuantityTensor, TIME] @system class Body(metaclass=Interface): - force: ForceField = field() - mass: MassField = field() + force: Force = field() + mass: Mass = field() @equation @@ -79,8 +74,8 @@ def weight_by_name(force: Force, mass: Mass) -> bool: def test_a_constant_in_another_unit_means_what_it_says() -> None: @system class Journey(metaclass=Interface): - distance: LengthField = field() - duration: TimeField = field() + distance: Length = field() + duration: Time = field() @equation def cruise(distance: Length, duration: Time) -> bool: @@ -96,15 +91,15 @@ def cruise(distance: Length, duration: Time) -> bool: def test_a_bare_unit_is_one_of_that_unit() -> None: @system class Route(metaclass=Interface): - distance: LengthField = field() - laps: DimensionlessField = field() + distance: Length = field() + laps: Dimensionless = field() @equation def lapping(distance: Length, laps: Dimensionless) -> bool: return distance == laps * kilometer with Implementation(Route, [lapping]): - result = Route(laps=Quantity(2.0, UNITLESS)).distance + result = Route(laps=2.0 * UNITLESS).distance assert result.value == pytest.approx(2000.0) assert result.unit == meter @@ -149,7 +144,7 @@ def scaled(y: float, x: float) -> bool: def test_a_plain_port_meeting_a_dimensionless_quantity_constant_raises() -> None: def doubled(y: float, x: float) -> bool: - return y == x * Quantity(2.0, UNITLESS) + return y == x * 2.0 * UNITLESS with pytest.raises(BiltEquationDimensionalityError, match="quantity constant"): equation(doubled) diff --git a/tests/dimensionality/test_quantity_wrapped_output.py b/tests/dimensionality/test_quantity_wrapped_output.py index 9901651a..e68c5395 100644 --- a/tests/dimensionality/test_quantity_wrapped_output.py +++ b/tests/dimensionality/test_quantity_wrapped_output.py @@ -10,22 +10,17 @@ from bilt.units.units import ampere, kilogram, millivolt, ohm, volt Current = typing.Annotated[Quantity, CURRENT] -CurrentField = typing.Annotated[Quantity | QuantityTensor, CURRENT] Dimensionless = typing.Annotated[Quantity, DIMENSIONLESS] -DimensionlessField = typing.Annotated[Quantity | QuantityTensor, DIMENSIONLESS] Mass = typing.Annotated[Quantity, MASS] -MassField = typing.Annotated[Quantity | QuantityTensor, MASS] Resistance = typing.Annotated[Quantity, RESISTANCE] -ResistanceField = typing.Annotated[Quantity | QuantityTensor, RESISTANCE] Voltage = typing.Annotated[Quantity, VOLTAGE] -VoltageField = typing.Annotated[Quantity | QuantityTensor, VOLTAGE] @system class Resistor(metaclass=Interface): - v: VoltageField = field() - i: CurrentField = field() - r: ResistanceField = field() + v: Voltage = field() + i: Current = field() + r: Resistance = field() @equation @@ -37,7 +32,7 @@ def test_a_declared_output_answers_in_the_coherent_si_unit_of_its_dimensionality with Implementation(Resistor, [ohms_law]): result = Resistor(i=2.0 * ampere, r=3000.0 * millivolt / ampere).v - assert isinstance(result, Quantity) + assert not isinstance(result, QuantityTensor) assert result.unit == volt assert result.value == pytest.approx(6.0) @@ -53,9 +48,9 @@ def test_a_declared_output_takes_its_dimensionality_from_its_own_declaration() - def test_a_ratio_answers_as_a_dimensionless_quantity_rather_than_a_bare_number() -> None: @system class Split(metaclass=Interface): - part: MassField = field() - whole: MassField = field() - fraction: DimensionlessField = field() + part: Mass = field() + whole: Mass = field() + fraction: Dimensionless = field() @equation def splitting(fraction: Dimensionless, part: Mass, whole: Mass) -> bool: @@ -64,6 +59,6 @@ def splitting(fraction: Dimensionless, part: Mass, whole: Mass) -> bool: with Implementation(Split, [splitting]): result = Split(part=2.0 * kilogram, whole=8.0 * kilogram).fraction - assert isinstance(result, Quantity) + assert not isinstance(result, QuantityTensor) assert result.unit.dimension == DIMENSIONLESS assert result.value == pytest.approx(0.25) diff --git a/tests/dimensionality/test_si_boundary.py b/tests/dimensionality/test_si_boundary.py index 9461d842..94877b6b 100644 --- a/tests/dimensionality/test_si_boundary.py +++ b/tests/dimensionality/test_si_boundary.py @@ -14,22 +14,17 @@ from bilt._backend._base_backend import Backend Acceleration = typing.Annotated[Quantity, LENGTH / TIME**2] -AccelerationField = typing.Annotated[Quantity | QuantityTensor, LENGTH / TIME**2] Area = typing.Annotated[Quantity, AREA] -AreaField = typing.Annotated[Quantity | QuantityTensor, AREA] Force = typing.Annotated[Quantity, FORCE] -ForceField = typing.Annotated[Quantity | QuantityTensor, FORCE] Length = typing.Annotated[Quantity, LENGTH] -LengthField = typing.Annotated[Quantity | QuantityTensor, LENGTH] Mass = typing.Annotated[Quantity, MASS] -MassField = typing.Annotated[Quantity | QuantityTensor, MASS] @system class Route(metaclass=Interface): - outbound: LengthField = field() - inbound: LengthField = field() - total: LengthField = field() + outbound: Length = field() + inbound: Length = field() + total: Length = field() @equation @@ -39,9 +34,9 @@ def journey(total: Length, outbound: Length, inbound: Length) -> bool: @system class Body(metaclass=Interface): - f: ForceField = field() - m: MassField = field() - a: AccelerationField = field() + f: Force = field() + m: Mass = field() + a: Acceleration = field() @equation @@ -61,7 +56,7 @@ def test_a_product_of_non_si_quantities_comes_back_in_coherent_si_units() -> Non with Implementation(Body, [newtons_second_law]): result = Body(m=1000.0 * gram, a=2.0 * meter / second**2).f - assert isinstance(result, Quantity) + assert not isinstance(result, QuantityTensor) assert result.value == pytest.approx(2.0) assert result.unit == newton @@ -70,7 +65,7 @@ def test_a_rearranged_equation_answers_in_coherent_si_units() -> None: with Implementation(Body, [newtons_second_law]): result = Body(f=6.0 * newton, a=2.0 * kilometer / hour**2).m - assert isinstance(result, Quantity) + assert not isinstance(result, QuantityTensor) assert result.value == pytest.approx(38880.0) assert result.unit == kilogram @@ -78,9 +73,9 @@ def test_a_rearranged_equation_answers_in_coherent_si_units() -> None: def test_quantities_that_contradict_a_declared_port_raise_at_instantiation() -> None: @system class Plot(metaclass=Interface): - width: LengthField = field() - depth: LengthField = field() - area: AreaField = field() + width: Length = field() + depth: Length = field() + area: Area = field() with pytest.raises(BiltInputDimensionalityError, match="'width'"): Plot(width=2.0 * kilogram, depth=3.0 * meter) diff --git a/tests/dimensionality/test_sub_systems.py b/tests/dimensionality/test_sub_systems.py index 8025893c..05d59b17 100644 --- a/tests/dimensionality/test_sub_systems.py +++ b/tests/dimensionality/test_sub_systems.py @@ -4,27 +4,23 @@ import pytest -from bilt import Implementation, Interface, QuantityTensor, equation, field, system +from bilt import Implementation, Interface, equation, field, system from bilt.errors import BiltEquationDimensionalityError, BiltImplementationDimensionalityError, BiltUnitsError from bilt.units import Quantity from bilt.units.dimensions import CURRENT, LENGTH, RESISTANCE, VOLTAGE from bilt.units.units import ampere, ohm, volt Current = typing.Annotated[Quantity, CURRENT] -CurrentField = typing.Annotated[Quantity | QuantityTensor, CURRENT] Length = typing.Annotated[Quantity, LENGTH] -LengthField = typing.Annotated[Quantity | QuantityTensor, LENGTH] Resistance = typing.Annotated[Quantity, RESISTANCE] -ResistanceField = typing.Annotated[Quantity | QuantityTensor, RESISTANCE] Voltage = typing.Annotated[Quantity, VOLTAGE] -VoltageField = typing.Annotated[Quantity | QuantityTensor, VOLTAGE] @system class Resistor(metaclass=Interface): - v: VoltageField = field() - i: CurrentField = field() - r: ResistanceField = field() + v: Voltage = field() + i: Current = field() + r: Resistance = field() @equation @@ -34,9 +30,9 @@ def ohms_law(v: Voltage, i: Current, r: Resistance) -> bool: @system class Component(metaclass=Interface): - voltage: VoltageField = field() - current: CurrentField = field() - resistance: ResistanceField = field() + voltage: Voltage = field() + current: Current = field() + resistance: Resistance = field() @equation @@ -76,7 +72,7 @@ def contradicting(resistance: Length, resistor: Resistor) -> bool: def test_a_dimensionality_a_grandchild_declares_reaches_the_grandparent() -> None: @system class Circuit(metaclass=Interface): - total: LengthField = field() + total: Length = field() with pytest.raises(BiltUnitsError, match=r"total_eq.*relates"): @@ -102,7 +98,7 @@ class PlainResistor(metaclass=Interface): @system class Parent(metaclass=Interface): - voltage: VoltageField = field() + voltage: Voltage = field() @equation def plain_voltage_eq(voltage: float, resistor: PlainResistor) -> bool: diff --git a/tests/dimensionality/test_tagged_quantities.py b/tests/dimensionality/test_tagged_quantities.py index be9d6d1f..ed853429 100644 --- a/tests/dimensionality/test_tagged_quantities.py +++ b/tests/dimensionality/test_tagged_quantities.py @@ -9,7 +9,7 @@ PYTHON_BACKEND, Implementation, Interface, - QuantityTensor, + Number, equation, field, system, @@ -39,30 +39,21 @@ mass_fraction = fraction * mass Mass = typing.Annotated[Quantity, MASS] -MassField = typing.Annotated[Quantity | QuantityTensor, MASS] FuelMass = typing.Annotated[Quantity, MASS * fuel] -FuelMassField = typing.Annotated[Quantity | QuantityTensor, MASS * fuel] Co2Mass = typing.Annotated[Quantity, MASS * co2] -Co2MassField = typing.Annotated[Quantity | QuantityTensor, MASS * co2] EmissionIndex = typing.Annotated[Quantity, (MASS * co2) / (MASS * fuel)] -EmissionIndexField = typing.Annotated[Quantity | QuantityTensor, (MASS * co2) / (MASS * fuel)] MassFraction = typing.Annotated[Quantity, DIMENSIONLESS * mass] -MassFractionField = typing.Annotated[Quantity | QuantityTensor, DIMENSIONLESS * mass] Hydrogen = typing.Annotated[Quantity, AMOUNT * hydrogen] -HydrogenField = typing.Annotated[Quantity | QuantityTensor, AMOUNT * hydrogen] CarbonMonoxide = typing.Annotated[Quantity, AMOUNT * carbon_monoxide] -CarbonMonoxideField = typing.Annotated[Quantity | QuantityTensor, AMOUNT * carbon_monoxide] SyngasRatio = typing.Annotated[Quantity, (AMOUNT * hydrogen) / (AMOUNT * carbon_monoxide)] -SyngasRatioField = typing.Annotated[Quantity | QuantityTensor, (AMOUNT * hydrogen) / (AMOUNT * carbon_monoxide)] GasTemperature = typing.Annotated[Quantity, TEMPERATURE * gas] -GasTemperatureField = typing.Annotated[Quantity | QuantityTensor, TEMPERATURE * gas] @system class Burn(metaclass=Interface): - burned: FuelMassField = field() - index: EmissionIndexField = field() - emitted: Co2MassField = field() + burned: FuelMass = field() + index: EmissionIndex = field() + emitted: Co2Mass = field() @equation @@ -72,9 +63,9 @@ def emission(emitted: Co2Mass, burned: FuelMass, index: EmissionIndex) -> bool: @system class Split(metaclass=Interface): - total: MassField = field() - x: MassFractionField = field() - part: MassField = field() + total: Mass = field() + x: MassFraction = field() + part: Mass = field() @equation @@ -84,15 +75,15 @@ def split(part: Mass, total: Mass, x: MassFraction) -> bool: @system class Fixed(metaclass=Interface): - burned: FuelMassField = field() - emitted: Co2MassField = field() + burned: FuelMass = field() + emitted: Co2Mass = field() @system class Weighed(metaclass=Interface): - burned: FuelMassField = field() + burned: FuelMass = field() grams: float = field() - emitted: Co2MassField = field() + emitted: Co2Mass = field() def test_a_tagged_port_answers_in_its_tagged_coherent_unit() -> None: @@ -114,9 +105,9 @@ def test_an_equation_is_solved_for_a_tagged_port_it_multiplies() -> None: def test_a_quotient_of_tagged_ports_answers_with_each_tag() -> None: @system class Syngas(metaclass=Interface): - h2: HydrogenField = field() - co: CarbonMonoxideField = field() - ratio: SyngasRatioField = field() + h2: Hydrogen = field() + co: CarbonMonoxide = field() + ratio: SyngasRatio = field() @equation def syngas_ratio(ratio: SyngasRatio, h2: Hydrogen, co: CarbonMonoxide) -> bool: @@ -167,10 +158,10 @@ def test_a_tagged_quantity_is_refused_at_an_untagged_port() -> None: def test_an_absolute_quantity_with_a_tag_is_refused() -> None: @system class Flue(metaclass=Interface): - temperature: GasTemperatureField = field() + temperature: GasTemperature = field() with pytest.raises(BiltInputDimensionalityError, match=r"Input 'temperature' of 'Flue'.*in a relative unit"): - Flue(temperature=Quantity(20.0, absolute_celsius) * gas) + Flue(temperature=20.0 * absolute_celsius * gas) def test_absolute_on_a_tagged_dimensionality_raises() -> None: @@ -178,7 +169,7 @@ def test_absolute_on_a_tagged_dimensionality_raises() -> None: @system class Flue(metaclass=Interface): - temperature: typing.Annotated[Quantity | QuantityTensor, TEMPERATURE * gas, ABSOLUTE] = field() + temperature: typing.Annotated[Quantity, TEMPERATURE * gas, ABSOLUTE] = field() assert "cannot be absolute" in str(raised.value) @@ -242,7 +233,7 @@ def emitted(burned: FuelMass) -> Co2Mass: def test_a_conversion_to_a_tagged_unit_takes_a_tagged_port_out_to_a_plain_one() -> None: @transform - def grams(burned: FuelMass) -> float: + def grams(burned: FuelMass) -> Number: return burned.convert_to(gram * fuel).value with Implementation(Weighed, [grams]): @@ -252,7 +243,7 @@ def grams(burned: FuelMass) -> float: def test_a_constructed_tagged_quantity_brings_a_plain_port_into_a_tagged_one() -> None: @transform def emitted(grams: float) -> Co2Mass: - return Quantity(grams, gram * co2) + return grams * (gram * co2) with Implementation(Weighed, [emitted]): answer = Weighed(grams=2000.0).emitted diff --git a/tests/dimensionality/test_tensor_ports.py b/tests/dimensionality/test_tensor_ports.py index 142961ce..50cd3d29 100644 --- a/tests/dimensionality/test_tensor_ports.py +++ b/tests/dimensionality/test_tensor_ports.py @@ -29,27 +29,21 @@ from bilt._backend._base_backend import Backend Mass = typing.Annotated[Quantity, MASS] -MassField = typing.Annotated[Quantity | QuantityTensor, MASS] MassOverADomain = typing.Annotated[QuantityTensor, MASS] -MassOverADomainField = typing.Annotated[QuantityTensor, MASS] Force = typing.Annotated[Quantity, FORCE] -ForceField = typing.Annotated[Quantity | QuantityTensor, FORCE] Acceleration = typing.Annotated[Quantity, LENGTH / TIME**2] -AccelerationField = typing.Annotated[Quantity | QuantityTensor, LENGTH / TIME**2] AbsoluteTemperature = typing.Annotated[Quantity, TEMPERATURE, ABSOLUTE] -AbsoluteTemperatureField = typing.Annotated[Quantity | QuantityTensor, TEMPERATURE, ABSOLUTE] co2 = Metadata("co2") TaggedMass = typing.Annotated[Quantity, MASS * co2] -TaggedMassField = typing.Annotated[Quantity | QuantityTensor, MASS * co2] time = dim("time") @system class Scale(metaclass=Interface): - m: MassField = field() - k: MassField = field() - doubled: MassField = field() - total: MassField = field() + m: Mass = field() + k: Mass = field() + doubled: Mass = field() + total: Mass = field() @equation @@ -64,8 +58,8 @@ def totalling(total: Mass, m: Mass, k: Mass) -> bool: @system class TaggedScale(metaclass=Interface): - m: TaggedMassField = field() - doubled: TaggedMassField = field() + m: TaggedMass = field() + doubled: TaggedMass = field() @equation @@ -75,8 +69,8 @@ def tagged_doubling(doubled: TaggedMass, m: TaggedMass) -> bool: @system class TensorScale(metaclass=Interface): - m: MassOverADomainField = field() - doubled: MassField = field() + m: MassOverADomain = field() + doubled: Mass = field() @equation @@ -97,8 +91,8 @@ def plain_doubling(doubled: Tensor, x: Tensor) -> bool: @system class AbsoluteThermometer(metaclass=Interface): - t: AbsoluteTemperatureField = field() - same: AbsoluteTemperatureField = field() + t: AbsoluteTemperature = field() + same: AbsoluteTemperature = field() @equation @@ -114,7 +108,7 @@ def _doubled(m: QuantityTensor) -> object: def test_a_declared_answer_over_a_domain_comes_back_in_the_coherent_unit() -> None: result = _doubled(tensor([1.0, 2.0], over=time, unit=tonne)) - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.unit is kilogram np.testing.assert_allclose(result.values, [2000.0, 4000.0]) @@ -122,7 +116,7 @@ def test_a_declared_answer_over_a_domain_comes_back_in_the_coherent_unit() -> No def test_a_declared_answer_over_a_domain_converts() -> None: result = _doubled(tensor([1.0, 2.0], over=time, unit=tonne)) - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) np.testing.assert_allclose(result.convert_to(tonne).values, [2.0, 4.0]) @@ -140,9 +134,9 @@ def test_an_answer_fed_back_in_as_an_input_is_read_in_its_own_unit() -> None: def test_a_tensor_and_a_scalar_quantity_may_meet_in_one_equation() -> None: masses = tensor([1.0, 2.0], over=time, unit=kilogram) with Implementation(Scale, [totalling]): - result = Scale(m=masses, k=Quantity(500.0, gram)).total + result = Scale(m=masses, k=500.0 * gram).total - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.unit is kilogram np.testing.assert_allclose(result.values, [1.5, 2.5]) @@ -152,7 +146,7 @@ def test_a_unit_carrying_tensor_is_checked_and_labelled_on_either_backend(backen with backend: result = _doubled(tensor([1.0, 2.0], over=time, unit=tonne)) - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.unit is kilogram np.testing.assert_allclose(result.values, [2000.0, 4000.0]) @@ -160,12 +154,12 @@ def test_a_unit_carrying_tensor_is_checked_and_labelled_on_either_backend(backen def test_a_scalar_declared_answer_is_a_quantity_holding_a_float() -> None: @transform def total(m: MassOverADomain) -> Mass: - return m.sum(time) # pyrefly: ignore[bad-return] # ty: ignore[invalid-return-type] + return m.sum(time) with Implementation(Scale, [total]): result = Scale(m=tensor([1.0, 2.0], over=time, unit=kilogram)).total - assert isinstance(result, Quantity) + assert not isinstance(result, QuantityTensor) assert type(result.value) is float assert result == 3.0 * kilogram @@ -174,17 +168,17 @@ def test_a_transform_bridges_a_plain_tensor_into_a_declared_port() -> None: @system class Rig(metaclass=Interface): masses_g: Tensor = field() - a: AccelerationField = field() - force: ForceField = field() + a: Acceleration = field() + force: Force = field() @transform def force(masses_g: Tensor, a: Acceleration) -> Force: - return masses_g * gram * a # pyrefly: ignore[bad-return] # ty: ignore[invalid-return-type] + return masses_g * gram * a with Implementation(Rig, [force]): result = Rig(masses_g=tensor([1000.0, 2000.0], over=time), a=2.0 * meter / second**2).force - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.unit is kilogram * meter / second**2 np.testing.assert_allclose(result.values, [2.0, 4.0]) @@ -192,12 +186,12 @@ def force(masses_g: Tensor, a: Acceleration) -> Force: def test_a_declared_tensor_parameter_is_erased_in_a_transform_body_as_a_scalar_is() -> None: @transform def doubled(m: Mass) -> Mass: - return Quantity(m.convert_to(gram).value * 2.0, gram) + return (m.convert_to(gram).value * 2.0) * gram with Implementation(Scale, [doubled]): result = Scale(m=tensor([1.0, 2.0], over=time, unit=kilogram)).doubled - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.unit is kilogram np.testing.assert_allclose(result.values, [2.0, 4.0]) @@ -205,18 +199,18 @@ def doubled(m: Mass) -> Mass: def test_an_absolute_declared_tensor_parameter_is_erased_with_its_offset() -> None: @system class Rig(metaclass=Interface): - t: AbsoluteTemperatureField = field() - in_celsius: AbsoluteTemperatureField = field() + t: AbsoluteTemperature = field() + in_celsius: AbsoluteTemperature = field() @transform def in_celsius(t: AbsoluteTemperature) -> AbsoluteTemperature: - return Quantity(t.convert_to(absolute_celsius).value, absolute_celsius) + return t.convert_to(absolute_celsius).value * absolute_celsius temperatures = tensor([273.15, 373.15], over=time, unit=abs(kelvin)) with Implementation(Rig, [in_celsius]): result = Rig(t=temperatures).in_celsius - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.unit is abs(kelvin) np.testing.assert_allclose(result.values, [273.15, 373.15]) @@ -226,7 +220,7 @@ def test_a_tagged_tensor_answers_in_its_tagged_coherent_unit() -> None: with Implementation(TaggedScale, [tagged_doubling]): result = TaggedScale(m=masses).doubled - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.unit == kilogram * co2 np.testing.assert_allclose(result.values, [2.0, 4.0]) @@ -239,8 +233,8 @@ def test_an_untagged_tensor_at_a_tagged_port_raises() -> None: def test_stripping_a_tag_in_a_transform_body_passes_a_tensor_through() -> None: @system class Rig(metaclass=Interface): - m: TaggedMassField = field() - plain: MassField = field() + m: TaggedMass = field() + plain: Mass = field() @transform def plain(m: TaggedMass) -> Mass: @@ -250,7 +244,7 @@ def plain(m: TaggedMass) -> Mass: with Implementation(Rig, [plain]): result = Rig(m=masses).plain - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.unit is kilogram np.testing.assert_allclose(result.values, [1.0, 2.0]) @@ -258,8 +252,8 @@ def plain(m: TaggedMass) -> Mass: def test_multiplying_by_a_tag_in_a_transform_body_passes_a_tensor_through() -> None: @system class Rig(metaclass=Interface): - m: MassField = field() - tagged: TaggedMassField = field() + m: Mass = field() + tagged: TaggedMass = field() @transform def tagged(m: Mass) -> TaggedMass: @@ -269,7 +263,7 @@ def tagged(m: Mass) -> TaggedMass: with Implementation(Rig, [tagged]): result = Rig(m=masses).tagged - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.unit == kilogram * co2 np.testing.assert_allclose(result.values, [1.0, 2.0]) @@ -294,7 +288,7 @@ def test_a_tensor_with_no_unit_at_a_plain_port_stays_bare() -> None: result = PlainScale(x=tensor([1.0, 2.0], over=time)).doubled assert isinstance(result, Tensor) - assert result.unit is None + assert not isinstance(result, Quantity) np.testing.assert_allclose(result.values, [2.0, 4.0]) @@ -303,7 +297,7 @@ def test_an_absolute_tensor_answers_in_the_absolute_coherent_unit() -> None: with Implementation(AbsoluteThermometer, [same_temperature]): result = AbsoluteThermometer(t=temperatures).same - assert isinstance(result, Tensor) + assert isinstance(result, QuantityTensor) assert result.unit is abs(kelvin) np.testing.assert_allclose(result.values, [273.15, 373.15]) @@ -311,7 +305,7 @@ def test_an_absolute_tensor_answers_in_the_absolute_coherent_unit() -> None: def test_a_dimensionality_differing_under_one_port_name_is_still_a_conflict() -> None: @system class Rig(metaclass=Interface): - m: MassOverADomainField = field() + m: MassOverADomain = field() doubled: typing.Annotated[QuantityTensor, FORCE] = field() @equation @@ -326,9 +320,9 @@ def doubling(doubled: Mass, m: Mass) -> bool: def test_rank_zero_tensor_outputs_can_be_reused(backend: Backend) -> None: @system class Chain(metaclass=Interface): - x: MassOverADomainField = field() - y: MassOverADomainField = field() - z: MassOverADomainField = field() + x: MassOverADomain = field() + y: MassOverADomain = field() + z: MassOverADomain = field() @equation def twice(y: Mass, x: Mass) -> bool: @@ -345,9 +339,9 @@ def thrice(z: Mass, y: Mass) -> bool: intermediate = staged.y sequential = staged.z - assert isinstance(intermediate, Tensor) - assert isinstance(direct, Tensor) - assert isinstance(sequential, Tensor) + assert isinstance(intermediate, QuantityTensor) + assert isinstance(direct, QuantityTensor) + assert isinstance(sequential, QuantityTensor) assert intermediate.domain.is_scalar assert direct.domain.is_scalar assert sequential.domain.is_scalar @@ -359,24 +353,19 @@ def thrice(z: Mass, y: Mass) -> bool: np.testing.assert_allclose(sequential.values, direct.values) -type FlexibleMass = typing.Annotated[Quantity | QuantityTensor, MASS] -type ScalarContractMass = typing.Annotated[Quantity, MASS] -type TensorContractMass = typing.Annotated[QuantityTensor, MASS] - - @system class GenericMassScale(metaclass=Interface): - m: FlexibleMass = field() - doubled: FlexibleMass = field() + m: Mass = field() + doubled: Mass = field() @equation -def generic_mass_copy(m: ScalarContractMass, doubled: ScalarContractMass) -> bool: +def generic_mass_copy(m: Mass, doubled: Mass) -> bool: return doubled == m def test_pointwise_quantity_boundary_accepts_scalar_and_tensor_without_ignores() -> None: - mass = Quantity(2.0, kilogram) + mass = 2.0 * kilogram varied = tensor([1.0, 2.0], over=time, unit=kilogram) typing.assert_type(varied, QuantityTensor) with Implementation(GenericMassScale, [generic_mass_copy]): @@ -386,38 +375,36 @@ def test_pointwise_quantity_boundary_accepts_scalar_and_tensor_without_ignores() np.testing.assert_array_equal(answer.values, [1.0, 2.0]) -def test_scalar_and_tensor_quantity_boundaries_reject_wrong_carrier() -> None: +def test_a_quantity_port_takes_any_shape_and_a_quantity_tensor_port_only_a_tensor() -> None: @system - class ScalarOnly(metaclass=Interface): - mass: ScalarContractMass = field() + class AnyShape(metaclass=Interface): + mass: Mass = field() @system class TensorOnly(metaclass=Interface): - mass: TensorContractMass = field() + mass: MassOverADomain = field() + masses = tensor([1.0], over=time, unit=kilogram) + assert AnyShape(mass=masses).mass is masses + assert AnyShape(mass=2.0 * kilogram).mass == 2.0 * kilogram with pytest.raises(BiltInputDimensionalityError): - ScalarOnly(mass=typing.cast("Quantity", tensor([1.0], over=time, unit=kilogram))) - with pytest.raises(BiltInputDimensionalityError): - TensorOnly(mass=typing.cast("QuantityTensor", Quantity(2.0, kilogram))) - - -type ConcreteTensorMass = typing.Annotated[QuantityTensor, MASS] + TensorOnly(mass=typing.cast("QuantityTensor", 2.0 * kilogram)) @system class ConcreteTensorTotals(metaclass=Interface): - m: ConcreteTensorMass = field() - total: FlexibleMass = field() + m: MassOverADomain = field() + total: Mass = field() @equation -def concrete_tensor_total(m: ConcreteTensorMass, total: Mass) -> bool: +def concrete_tensor_total(m: MassOverADomain, total: Mass) -> bool: return total == m.sum(time) -def _typed_tensor_reduction(value: QuantityTensor) -> Tensor: +def _typed_tensor_reduction(value: QuantityTensor) -> QuantityTensor: result = value.sum(time) - typing.assert_type(result, Tensor) + typing.assert_type(result, QuantityTensor) return result @@ -443,7 +430,7 @@ class RequiredTimeMass(metaclass=Interface): @system class RequiredTimeOutput(metaclass=Interface): - m: FlexibleMass = field() + m: Mass = field() doubled: TimeDomainMass = field() @@ -463,5 +450,5 @@ def test_computed_output_obeys_required_tensor_domain() -> None: with pytest.raises(BiltInputDimensionalityError, match="missing dimensions: time"): _ = RequiredTimeOutput(m=tensor([1.0, 2.0], over=scenario, unit=kilogram)).doubled ok = RequiredTimeOutput(m=tensor([1.0, 2.0], over=time, unit=kilogram)).doubled - assert isinstance(ok, Tensor) + assert isinstance(ok, QuantityTensor) assert ok.domain.dims == (time,) diff --git a/tests/dimensionality/test_units_in_transform_bodies.py b/tests/dimensionality/test_units_in_transform_bodies.py index 1a12fd08..047880cd 100644 --- a/tests/dimensionality/test_units_in_transform_bodies.py +++ b/tests/dimensionality/test_units_in_transform_bodies.py @@ -5,7 +5,16 @@ import pytest -from bilt import JAX_BACKEND, PYTHON_BACKEND, Implementation, Interface, QuantityTensor, field, system, transform +from bilt import ( + JAX_BACKEND, + PYTHON_BACKEND, + Implementation, + Interface, + Number, + field, + system, + transform, +) from bilt.errors import BiltDefinitionError from bilt.units import Quantity, meter, units from bilt.units.dimensions import LENGTH @@ -16,17 +25,16 @@ from bilt.core._transform import BasicTransform Length = typing.Annotated[Quantity, LENGTH] -LengthField = typing.Annotated[Quantity | QuantityTensor, LENGTH] @system class Stretch(metaclass=Interface): - length: LengthField = field() - stretched: LengthField = field() + length: Length = field() + stretched: Length = field() span_km: float = field() -def _stretch(stretched: BasicTransform) -> Quantity | QuantityTensor: +def _stretch(stretched: BasicTransform) -> Quantity: with Implementation(Stretch, [stretched]): return Stretch(length=1.0 * kilometer).stretched @@ -41,14 +49,6 @@ def stretched(length: Length) -> Length: assert _stretch(stretched) == 1000.5 * meter -def test_a_constructed_quantity_means_the_same_as_a_product() -> None: - @transform - def stretched(length: Length) -> Length: - return length + Quantity(1.0, kilometer) - - assert _stretch(stretched) == 2000.0 * meter - - def test_a_dimensionality_property_is_read() -> None: @transform def stretched(length: Length) -> Length: @@ -140,56 +140,20 @@ def stretched(length: Length) -> Length: def test_a_converted_value_takes_a_declared_port_out_to_a_plain_one() -> None: @transform - def span_km(length: Length) -> float: + def span_km(length: Length) -> Number: return length.convert_to(kilometer).value with Implementation(Stretch, [span_km]): assert Stretch(length=1000.0 * meter).span_km == 1.0 -def test_a_constructed_quantity_brings_a_plain_port_into_the_unit_system() -> None: - @transform - def stretched(span_km: float) -> Length: - return Quantity(span_km, kilometer) - - with Implementation(Stretch, [stretched]): - assert Stretch(span_km=2.0).stretched == 2000.0 * meter - - -def test_a_constructed_quantity_takes_its_unit_by_keyword() -> None: - @transform - def stretched(span_km: float) -> Length: - return Quantity(span_km, unit=kilometer) - - with Implementation(Stretch, [stretched]): - assert Stretch(span_km=2.0).stretched == 2000.0 * meter - - -def test_a_constructed_quantity_takes_both_arguments_by_keyword() -> None: - @transform - def stretched(span_km: float) -> Length: - return Quantity(value=span_km, unit=kilometer) - - with Implementation(Stretch, [stretched]): - assert Stretch(span_km=2.0).stretched == 2000.0 * meter - - -def test_a_constructed_quantity_takes_its_keywords_in_either_order() -> None: - @transform - def stretched(span_km: float) -> Length: - return Quantity(unit=kilometer, value=span_km) - - with Implementation(Stretch, [stretched]): - assert Stretch(span_km=2.0).stretched == 2000.0 * meter - - def test_a_conversion_in_one_transform_and_a_reading_in_the_next_agree_with_python() -> None: @transform def stretched(length: Length) -> Length: return length.convert_to(kilometer) @transform - def span_km(stretched: Length) -> float: + def span_km(stretched: Length) -> Number: return stretched.convert_to(kilometer).value with Implementation(Stretch, [stretched, span_km]): @@ -236,7 +200,7 @@ def stretched(length: Length) -> Length: def test_an_absolute_unit_as_a_scale_is_refused() -> None: with pytest.raises( BiltDefinitionError, - match=r"`absolute_celsius` is an absolute unit.*write `Quantity\(, absolute_celsius\)`", + match=r"`absolute_celsius` is an absolute unit.*as in ` \* absolute_celsius`", ): @transform @@ -252,7 +216,7 @@ def test_converting_a_parameter_to_a_unit_of_another_dimensionality_is_refused() ): @transform - def span_km(length: Length) -> float: + def span_km(length: Length) -> Number: return length.convert_to(second).value diff --git a/tests/typing/negative_quantity_cases.py.txt b/tests/typing/negative_quantity_cases.py.txt index 0706a0cb..ed23e0fd 100644 --- a/tests/typing/negative_quantity_cases.py.txt +++ b/tests/typing/negative_quantity_cases.py.txt @@ -8,53 +8,55 @@ and then removes the file. from typing import Annotated -from bilt import Interface, Quantity, QuantityTensor, Tensor, dim, field, system, tensor +from bilt import Interface, Number, Quantity, QuantityTensor, Tensor, dim, field, system, tensor from bilt.units import kilogram from bilt.units.dimensions import MASS time = dim("time") -scalar = Quantity(2.0, kilogram) +scalar = 2.0 * kilogram labelled = tensor([1.0, 2.0], over=time, unit=kilogram) unitless = tensor([1.0, 2.0], over=time) -def takes_quantity(mass: Quantity | QuantityTensor) -> None: +def takes_quantity(mass: Quantity) -> None: pass -def takes_scalar(mass: Quantity) -> None: +def takes_tensor(mass: QuantityTensor) -> None: pass -def takes_tensor(mass: QuantityTensor) -> None: +def takes_unitless_tensor(value: Tensor) -> None: pass +def takes_number(value: Number) -> None: + pass + + +# Units: a unitless value is not a quantity, and a quantity is not unitless. takes_quantity(unitless) # expect: unlabelled-tensor-is-not-a-quantity -takes_scalar(labelled) # expect: tensor-is-not-a-scalar-quantity +takes_number(scalar) # expect: quantity-is-not-a-number +takes_number(labelled) # expect: quantity-tensor-is-not-a-number +takes_unitless_tensor(labelled) # expect: quantity-tensor-is-not-a-unitless-tensor + +# Shape: a scalar quantity is not a tensor, so it cannot be reduced. takes_tensor(scalar) # expect: scalar-is-not-a-tensor-quantity +takes_unitless_tensor(scalar) # expect: scalar-quantity-is-not-a-tensor scalar.sum(time) # expect: scalar-quantity-has-no-tensor-reduction - - takes_tensor(unitless) # expect: unitless-tensor-is-not-quantity-tensor -@system -class ScalarOnly(metaclass=Interface): - mass: Annotated[Quantity, MASS] = field() - - @system class TensorOnly(metaclass=Interface): mass: Annotated[QuantityTensor, MASS] = field() -ScalarOnly(mass=labelled) # expect: scalar-system-rejects-tensor TensorOnly(mass=scalar) # expect: tensor-system-rejects-scalar -# Pointwise quantities must still be unit-bearing. +# The old pointwise union means the same as Quantity, so it must still be unit-bearing. PointwiseMass = Annotated[Quantity | QuantityTensor, MASS] @@ -66,7 +68,13 @@ takes_pointwise_mass(unitless) # expect: unitless-tensor-not-pointwise-quantity @system class UnitlessFlexible(metaclass=Interface): - value: float | Tensor = field() + value: Number = field() UnitlessFlexible(value=scalar) # expect: unitless-union-rejects-scalar-quantity + + +# Operator results keep or lack units exactly as their operands do. +takes_quantity(unitless * 2.0) # expect: scaled-unitless-tensor-is-not-a-quantity +takes_tensor(scalar**2) # expect: scalar-power-is-not-a-tensor-quantity +takes_tensor(labelled.value) # expect: tensor-magnitude-is-not-a-quantity diff --git a/tests/typing/test_negative_quantity_checkers.py b/tests/typing/test_negative_quantity_checkers.py index a6fbe737..cc88d91d 100644 --- a/tests/typing/test_negative_quantity_checkers.py +++ b/tests/typing/test_negative_quantity_checkers.py @@ -32,10 +32,6 @@ "ty": frozenset({"invalid-argument-type"}), "pyrefly": frozenset({"bad-argument-type"}), }, - "tensor-is-not-a-scalar-quantity": { - "ty": frozenset({"invalid-argument-type"}), - "pyrefly": frozenset({"bad-argument-type"}), - }, "scalar-is-not-a-tensor-quantity": { "ty": frozenset({"invalid-argument-type"}), "pyrefly": frozenset({"bad-argument-type"}), @@ -48,11 +44,35 @@ "ty": frozenset({"invalid-argument-type"}), "pyrefly": frozenset({"bad-argument-type"}), }, - "scalar-system-rejects-tensor": { + "tensor-system-rejects-scalar": { "ty": frozenset({"invalid-argument-type"}), "pyrefly": frozenset({"bad-argument-type"}), }, - "tensor-system-rejects-scalar": { + "scaled-unitless-tensor-is-not-a-quantity": { + "ty": frozenset({"invalid-argument-type"}), + "pyrefly": frozenset({"bad-argument-type"}), + }, + "scalar-power-is-not-a-tensor-quantity": { + "ty": frozenset({"invalid-argument-type"}), + "pyrefly": frozenset({"bad-argument-type"}), + }, + "tensor-magnitude-is-not-a-quantity": { + "ty": frozenset({"invalid-argument-type"}), + "pyrefly": frozenset({"bad-argument-type"}), + }, + "quantity-is-not-a-number": { + "ty": frozenset({"invalid-argument-type"}), + "pyrefly": frozenset({"bad-argument-type"}), + }, + "quantity-tensor-is-not-a-number": { + "ty": frozenset({"invalid-argument-type"}), + "pyrefly": frozenset({"bad-argument-type"}), + }, + "quantity-tensor-is-not-a-unitless-tensor": { + "ty": frozenset({"invalid-argument-type"}), + "pyrefly": frozenset({"bad-argument-type"}), + }, + "scalar-quantity-is-not-a-tensor": { "ty": frozenset({"invalid-argument-type"}), "pyrefly": frozenset({"bad-argument-type"}), }, diff --git a/tests/typing/test_pointwise_quantity_annotations.py b/tests/typing/test_pointwise_quantity_annotations.py index b57ffe0d..c5347ec2 100644 --- a/tests/typing/test_pointwise_quantity_annotations.py +++ b/tests/typing/test_pointwise_quantity_annotations.py @@ -19,14 +19,13 @@ from bilt.units.dimensions import MASS Mass = typing.Annotated[Quantity, MASS] -PointwiseMass = typing.Annotated[Quantity | QuantityTensor, MASS] time = dim("time") @system class DoubleMass(metaclass=Interface): - mass: PointwiseMass = field() - doubled: PointwiseMass = field() + mass: Mass = field() + doubled: Mass = field() @equation @@ -36,10 +35,10 @@ def doubling(mass: Mass, doubled: Mass) -> bool: def test_pointwise_quantity_alias_supports_scalar_and_tensor_values() -> None: with Implementation(DoubleMass, [doubling]): - scalar = DoubleMass(mass=Quantity(2.0, kilogram)).doubled + scalar = DoubleMass(mass=2.0 * kilogram).doubled varied = DoubleMass(mass=tensor([2.0, 3.0], over=time, unit=kilogram)).doubled - assert isinstance(scalar, Quantity) + assert not isinstance(scalar, QuantityTensor) assert scalar.value == 2.0 * 2.0 assert isinstance(varied, QuantityTensor) assert varied.unit == kilogram diff --git a/tests/typing/test_quantity_protocols.py b/tests/typing/test_quantity_protocols.py new file mode 100644 index 00000000..3a50a35c --- /dev/null +++ b/tests/typing/test_quantity_protocols.py @@ -0,0 +1,116 @@ +"""Check the four public annotations: what satisfies each, and what arithmetic on them gives. + +| | Any shape | Must be a tensor | +|----------|------------|------------------| +| Units | `Quantity` | `QuantityTensor` | +| No units | `Number` | `Tensor` | + +The typing-only functions are checked by pyrefly and ty over this module. Values a +protocol must reject are in `negative_quantity_cases.py.txt`. The runtime tests check +that `isinstance` agrees with the grid for the values users create. +""" + +import typing + +from bilt import Number, Quantity, QuantityTensor, Tensor, dim, tensor +from bilt.units import kilogram, meter + +if typing.TYPE_CHECKING: + from bilt.core._tensors._tensors import _QuantityTensor, _Tensor + from bilt.units._quantities import _Quantity + +time = dim("time") + + +def _concrete_values_satisfy_their_protocols(q: _Quantity, qt: _QuantityTensor, t: _Tensor) -> None: + _: Quantity = q + _ = qt + _qt: QuantityTensor = qt + _t: Tensor = t + _n: Number = t + _n = 2.0 + _n = 2 + + +def _a_quantity_tensor_is_a_quantity(qt: QuantityTensor) -> Quantity: + return qt + + +def _creating_values_gives_the_public_types() -> None: + typing.assert_type(2.0 * kilogram, Quantity) + typing.assert_type(tensor([1.0], over=time, unit=kilogram), QuantityTensor) + typing.assert_type(tensor([1.0], over=time), Tensor) + typing.assert_type(tensor([1.0], over=time) * meter, QuantityTensor) + + +def _quantity_arithmetic_stays_a_quantity(x: Quantity, y: Quantity) -> None: + typing.assert_type(x + y, Quantity) + typing.assert_type(x - y, Quantity) + typing.assert_type(x * y, Quantity) + typing.assert_type(x / y, Quantity) + typing.assert_type(x * 2.0, Quantity) + typing.assert_type(2.0 * x, Quantity) + typing.assert_type(2.0 / x, Quantity) + typing.assert_type(x**2, Quantity) + typing.assert_type(-x, Quantity) + typing.assert_type(x * meter, Quantity) + typing.assert_type(x / meter, Quantity) + typing.assert_type(x.convert_to(meter), Quantity) + typing.assert_type(x.strip_metadata(), Quantity) + typing.assert_type(x < y, bool) + typing.assert_type(x.value, Number) + + +def _quantity_tensor_arithmetic_stays_a_quantity_tensor(x: QuantityTensor, q: Quantity, t: Tensor) -> None: + typing.assert_type(x + x, QuantityTensor) + typing.assert_type(x + q, QuantityTensor) + typing.assert_type(x - q, QuantityTensor) + typing.assert_type(x * q, QuantityTensor) + typing.assert_type(x / q, QuantityTensor) + typing.assert_type(x * t, QuantityTensor) + typing.assert_type(t * x, QuantityTensor) + typing.assert_type(x * 2.0, QuantityTensor) + typing.assert_type(2.0 * x, QuantityTensor) + typing.assert_type(x**2, QuantityTensor) + typing.assert_type(x * meter, QuantityTensor) + typing.assert_type(x.sum(time), QuantityTensor) + typing.assert_type(x.isel(time, 0), QuantityTensor) + typing.assert_type(x.value, Tensor) + + +def _a_unitless_tensor_gains_a_unit_only_from_a_quantity_or_unit(t: Tensor, q: Quantity) -> None: + typing.assert_type(t + t, Tensor) + typing.assert_type(t + 1.0, Tensor) + typing.assert_type(1.0 - t, Tensor) + typing.assert_type(t * 2.0, Tensor) + typing.assert_type(t**2, Tensor) + typing.assert_type(t.mean(time), Tensor) + typing.assert_type(t * q, QuantityTensor) + typing.assert_type(q * t, QuantityTensor) + typing.assert_type(t / q, QuantityTensor) + typing.assert_type(t * meter, QuantityTensor) + + +def _number_arithmetic_stays_a_number(n: Number) -> None: + typing.assert_type(n + n, Number) + typing.assert_type(n * 2.0, Number) + typing.assert_type(n + 1.0, Number) + typing.assert_type(n**2, Number) + + +def test_isinstance_follows_the_grid_for_created_values() -> None: + scalar = 2.0 * kilogram + labelled = tensor([1.0, 2.0], over=time, unit=kilogram) + unitless = tensor([1.0, 2.0], over=time) + + assert isinstance(scalar, Quantity) + assert not isinstance(scalar, Tensor) + assert not isinstance(scalar, QuantityTensor) + + assert isinstance(labelled, Quantity) + assert isinstance(labelled, QuantityTensor) + + assert isinstance(unitless, Tensor) + assert not isinstance(unitless, Quantity) + assert isinstance(unitless, Number) + assert isinstance(2.0, Number) diff --git a/tests/typing/test_tensor_operator_typing.py b/tests/typing/test_tensor_operator_typing.py new file mode 100644 index 00000000..624aff8f --- /dev/null +++ b/tests/typing/test_tensor_operator_typing.py @@ -0,0 +1,98 @@ +"""Check that the concrete tensor classes' operators keep units at the type level. + +These are the private classes behind the public protocols (see +`test_quantity_protocols.py`). Tensor arithmetic is symbolic: it raises outside a +Bilt model, so these cases are checked by pyrefly and ty over this module rather +than run. The one runtime test confirms that the overrides on the concrete quantity +tensor still label with units. +""" + +import typing + +import numpy as np + +from bilt import QuantityTensor, dim, tensor +from bilt.core._tensors._tensors import _QuantityTensor, _Tensor +from bilt.units import kilogram, meter +from bilt.units._quantities import _Quantity + +time = dim("time") + + +def _quantity_tensor_arithmetic_keeps_its_unit(qt: _QuantityTensor, t: _Tensor) -> None: + typing.assert_type(qt + qt, _QuantityTensor) + typing.assert_type(qt - qt, _QuantityTensor) + typing.assert_type(-qt, _QuantityTensor) + typing.assert_type(+qt, _QuantityTensor) + typing.assert_type(abs(qt), _QuantityTensor) + typing.assert_type(qt * 2.0, _QuantityTensor) + typing.assert_type(2.0 * qt, _QuantityTensor) + typing.assert_type(qt * 2, _QuantityTensor) + typing.assert_type(qt / 2.0, _QuantityTensor) + typing.assert_type(2.0 / qt, _QuantityTensor) + typing.assert_type(qt * qt, _QuantityTensor) + typing.assert_type(qt / qt, _QuantityTensor) + typing.assert_type(qt * t, _QuantityTensor) + typing.assert_type(t * qt, _QuantityTensor) + typing.assert_type(qt / t, _QuantityTensor) + typing.assert_type(t / qt, _QuantityTensor) + typing.assert_type(qt**2, _QuantityTensor) + typing.assert_type(qt**0.5, _QuantityTensor) + + +def _mixed_scalar_and_tensor_quantities_give_a_tensor(q: _Quantity, qt: _QuantityTensor, t: _Tensor) -> None: + typing.assert_type(q + qt, _QuantityTensor) + typing.assert_type(qt + q, _QuantityTensor) + typing.assert_type(q - qt, _QuantityTensor) + typing.assert_type(qt - q, _QuantityTensor) + typing.assert_type(q * qt, _QuantityTensor) + typing.assert_type(qt * q, _QuantityTensor) + typing.assert_type(q / qt, _QuantityTensor) + typing.assert_type(qt / q, _QuantityTensor) + typing.assert_type(q * t, _QuantityTensor) + typing.assert_type(t * q, _QuantityTensor) + typing.assert_type(t / q, _QuantityTensor) + typing.assert_type(q / t, _QuantityTensor) + + +def _unitless_tensor_arithmetic_stays_unitless(t: _Tensor) -> None: + typing.assert_type(t + t, _Tensor) + typing.assert_type(t * 2.0, _Tensor) + typing.assert_type(2.0 / t, _Tensor) + typing.assert_type(-t, _Tensor) + typing.assert_type(t**2, _Tensor) + typing.assert_type(2.0**t, _Tensor) + typing.assert_type(t * meter, _QuantityTensor) + + +def _reductions_and_selections_keep_the_carrier(qt: _QuantityTensor, t: _Tensor) -> None: + typing.assert_type(qt.sum(time), _QuantityTensor) + typing.assert_type(qt.mean(time), _QuantityTensor) + typing.assert_type(qt.min(time), _QuantityTensor) + typing.assert_type(qt.max(time), _QuantityTensor) + typing.assert_type(qt.prod(time), _QuantityTensor) + typing.assert_type(qt.isel(time, 0), _QuantityTensor) + typing.assert_type(t.sum(time), _Tensor) + typing.assert_type(qt.value, _Tensor) + + +def _union_arithmetic_type_checks(u: _Quantity | _QuantityTensor) -> None: + typing.assert_type(u + u, _Quantity | _QuantityTensor) + typing.assert_type(u - u, _Quantity | _QuantityTensor) + typing.assert_type(u * u, _Quantity | _QuantityTensor) + typing.assert_type(u / u, _Quantity | _QuantityTensor) + typing.assert_type(u * 2.0, _Quantity | _QuantityTensor) + typing.assert_type(u**2, _Quantity | _QuantityTensor) + + +def test_quantity_tensor_overrides_still_label_with_units() -> None: + labelled = tensor([1.0, 2.0], over=time, unit=kilogram) + + for result, unit in ( + (labelled * meter, kilogram * meter), + (meter * labelled, meter * kilogram), + (labelled / meter, kilogram / meter), + ): + assert isinstance(result, QuantityTensor) + assert result.unit == unit + np.testing.assert_array_equal(result.values, [1.0, 2.0]) diff --git a/tests/units/test_quantities.py b/tests/units/test_quantities.py index 04f229db..cb5228f0 100644 --- a/tests/units/test_quantities.py +++ b/tests/units/test_quantities.py @@ -5,7 +5,7 @@ from bilt.errors import BiltDimensionalityError, BiltUnitError from bilt.units._metadata import Metadata -from bilt.units._quantities import Quantity +from bilt.units._quantities import _Quantity from bilt.units._units import ( UNITLESS, Unit, @@ -53,15 +53,15 @@ class TestQuantity: ), ) def test_equality( - left: Quantity, - right: Quantity, + left: _Quantity, + right: _Quantity, expected: bool, ) -> None: assert (left == right) is expected @staticmethod def test_positive_and_rounding() -> None: - quantity = -2.345 * meter + quantity = _Quantity(-2.345, meter) assert +quantity == -2.345 * meter assert round(quantity, 2) == -2.35 * meter @@ -75,8 +75,8 @@ def test_positive_and_rounding() -> None: ), ) def test_negation( - quantity: Quantity, - expected: Quantity, + quantity: _Quantity, + expected: _Quantity, ) -> None: assert -quantity == expected @@ -89,8 +89,8 @@ def test_negation( ), ) def test_absolute( - quantity: Quantity, - expected: Quantity, + quantity: _Quantity, + expected: _Quantity, ) -> None: assert abs(quantity) == expected @@ -107,15 +107,15 @@ def test_absolute( ), ) def test_addition( - left: Quantity, - right: Quantity, - expected: Quantity, + left: _Quantity, + right: _Quantity, + expected: _Quantity, ) -> None: assert left + right == expected @staticmethod def test_sum_uses_reflected_addition() -> None: - assert sum((1.0 * meter, 2.0 * meter)) == 3.0 * meter + assert sum((_Quantity(1.0, meter), _Quantity(2.0, meter))) == 3.0 * meter @staticmethod @pytest.mark.parametrize( @@ -130,8 +130,8 @@ def test_sum_uses_reflected_addition() -> None: ), ) def test_addition_dimensionality_error_if_units_dimensionally_inconsistent( - left: Quantity, - right: Quantity, + left: _Quantity, + right: _Quantity, ) -> None: with pytest.raises( BiltDimensionalityError, @@ -154,8 +154,8 @@ def test_addition_dimensionality_error_if_units_dimensionally_inconsistent( ), ) def test_addition_unit_error_if_units_not_equal( - left: Quantity, - right: Quantity, + left: _Quantity, + right: _Quantity, ) -> None: with pytest.raises( BiltUnitError, @@ -186,8 +186,8 @@ def test_addition_unit_error_if_units_not_equivalent() -> None: ), ) def test_addition_dimensionality_error_if_unit_metadata_not_equal( - left: Quantity, - right: Quantity, + left: _Quantity, + right: _Quantity, ) -> None: with pytest.raises( BiltDimensionalityError, @@ -214,8 +214,8 @@ def test_addition_rejects_two_absolute_quantities() -> None: ), ) def test_addition_type_error_if_other_is_not_quantity( - left: Quantity, - right: Quantity, + left: _Quantity, + right: _Quantity, ) -> None: with pytest.raises(TypeError): _ = left + right @@ -245,9 +245,9 @@ def test_addition_rejects_absolute_and_differently_scaled_relative_units() -> No ), ) def test_addition_absolute_and_relative_returns_absolute_quantity( - left: Quantity, - right: Quantity, - expected: Quantity, + left: _Quantity, + right: _Quantity, + expected: _Quantity, ) -> None: assert left + right == expected @@ -269,9 +269,9 @@ def test_addition_absolute_and_relative_returns_absolute_quantity( ), ) def test_subtraction( - left: Quantity, - right: Quantity, - expected: Quantity, + left: _Quantity, + right: _Quantity, + expected: _Quantity, ) -> None: assert left - right == expected @@ -280,36 +280,36 @@ def test_subtraction( ("left", "right", "expected"), ( ( - Quantity(2.0, second), - Quantity(2.0, ampere), - Quantity(4.0, ampere * second), + _Quantity(2.0, second), + _Quantity(2.0, ampere), + _Quantity(4.0, ampere * second), ), ( - Quantity(2.0, second), + _Quantity(2.0, second), ampere, - Quantity(2.0, ampere * second), + _Quantity(2.0, ampere * second), ), ( - Quantity(2.0, kilogram), + _Quantity(2.0, kilogram), co2, - Quantity(2.0, kilogram * co2), + _Quantity(2.0, kilogram * co2), ), ( - Quantity(2.0, kilogram), + _Quantity(2.0, kilogram), 2.0, - Quantity(4.0, kilogram), + _Quantity(4.0, kilogram), ), ( - Quantity(2.0, kilogram * co2), + _Quantity(2.0, kilogram * co2), 2.0, - Quantity(4.0, kilogram * co2), + _Quantity(4.0, kilogram * co2), ), ), ) def test_multiplication_quantity_left( - left: Quantity, - right: Unit | Quantity | Metadata | float, - expected: Quantity, + left: _Quantity, + right: Unit | _Quantity | Metadata | float, + expected: _Quantity, ) -> None: assert left * right == expected @@ -318,26 +318,26 @@ def test_multiplication_quantity_left( ("left", "right", "expected"), ( ( - Quantity(2.0, second), - Quantity(2.0, ampere), - Quantity(4.0, ampere * second), + _Quantity(2.0, second), + _Quantity(2.0, ampere), + _Quantity(4.0, ampere * second), ), ( 2.0, - Quantity(2.0, kilogram), - Quantity(4.0, kilogram), + _Quantity(2.0, kilogram), + _Quantity(4.0, kilogram), ), ( 2.0, - Quantity(2.0, kilogram * co2), - Quantity(4.0, kilogram * co2), + _Quantity(2.0, kilogram * co2), + _Quantity(4.0, kilogram * co2), ), ), ) def test_multiplication_quantity_right( - left: Quantity | float, - right: Quantity, - expected: Quantity, + left: _Quantity | float, + right: _Quantity, + expected: _Quantity, ) -> None: assert left * right == expected @@ -346,26 +346,26 @@ def test_multiplication_quantity_right( ("left", "right", "expected"), ( ( - Quantity(4.0, meter), - Quantity(2.0, second), - Quantity(2.0, meter / second), + _Quantity(4.0, meter), + _Quantity(2.0, second), + _Quantity(2.0, meter / second), ), ( - Quantity(2.0, meter / second), + _Quantity(2.0, meter / second), 2.0, - Quantity(1.0, meter / second), + _Quantity(1.0, meter / second), ), ( - Quantity(2.0, meter), + _Quantity(2.0, meter), second, - Quantity(2.0, meter / second), + _Quantity(2.0, meter / second), ), ), ) def test_division_quantity_numerator( - left: Quantity, - right: Quantity | Unit | float, - expected: Quantity, + left: _Quantity, + right: _Quantity | Unit | float, + expected: _Quantity, ) -> None: assert left / right == expected @@ -374,26 +374,26 @@ def test_division_quantity_numerator( ("left", "right", "expected"), ( ( - Quantity(4.0, meter), - Quantity(2.0, second), - Quantity(2.0, meter / second), + _Quantity(4.0, meter), + _Quantity(2.0, second), + _Quantity(2.0, meter / second), ), ( 1.0, - Quantity(2.0, second), - Quantity(0.5, 1 / second), + _Quantity(2.0, second), + _Quantity(0.5, 1 / second), ), ( meter, - Quantity(2.0, second), - Quantity(0.5, meter / second), + _Quantity(2.0, second), + _Quantity(0.5, meter / second), ), ), ) def test_division_quantity_denominator( - left: Quantity | Unit | float, - right: Quantity, - expected: Quantity, + left: _Quantity | Unit | float, + right: _Quantity, + expected: _Quantity, ) -> None: assert left / right == expected @@ -434,9 +434,9 @@ def test_division_quantity_denominator( ), ) def test_exponentiation_unitless_unit( - quantity: Quantity, + quantity: _Quantity, exponent: float, - expected: Quantity, + expected: _Quantity, ) -> None: assert quantity**exponent == expected @@ -462,9 +462,9 @@ def test_exponentiation_unitless_unit( ), ) def test_exponentiation_int_exponent( - quantity: Quantity, + quantity: _Quantity, exponent: int, - expected: Quantity, + expected: _Quantity, ) -> None: assert quantity**exponent == expected @@ -478,10 +478,10 @@ def test_exponentiation_int_exponent( ), ) def test_exponentiation_float_exponent_raises_type_error( - quantity: Quantity, + quantity: _Quantity, exponent: float, ) -> None: - message = re.escape("unsupported operand type(s) for ** or pow(): 'Quantity' and 'float'") + message = re.escape("unsupported operand type(s) for ** or pow(): '_Quantity' and 'float'") with pytest.raises(TypeError, match=message): _ = quantity**exponent @@ -514,8 +514,8 @@ def test_exponentiation_float_exponent_raises_type_error( ) def test_exponentiation_float_base( base: float, - quantity: Quantity, - expected: Quantity, + quantity: _Quantity, + expected: _Quantity, ) -> None: assert base**quantity == expected @@ -529,9 +529,9 @@ def test_exponentiation_float_base( ) def test_exponentiation_float_base_non_dimensionless_quantity_raises_type_error( base: float, - quantity: Quantity, + quantity: _Quantity, ) -> None: - message = re.escape("unsupported operand type(s) for ** or pow(): 'float' and 'Quantity'") + message = re.escape("unsupported operand type(s) for ** or pow(): 'float' and '_Quantity'") with pytest.raises(TypeError, match=message): _ = base**quantity @@ -616,9 +616,9 @@ def test_subtraction_unit_error_if_absolute_subtracted_from_relative() -> None: ), ) def test_quantity_cast_to( - quantity: Quantity, + quantity: _Quantity, unit: Unit, - expected: Quantity, + expected: _Quantity, ) -> None: result = quantity.cast_to(unit) @@ -640,7 +640,7 @@ def test_quantity_cast_to( ), ) def test_quantity_cast_to_unit_error_if_units_not_equivalent( - quantity: Quantity, + quantity: _Quantity, unit: Unit, ) -> None: with pytest.raises(BiltUnitError, match="Cannot cast quantity"): @@ -698,9 +698,9 @@ def test_quantity_cast_to_unit_error_if_units_not_equivalent( ), ) def test_quantity_convert_to( - quantity: Quantity, + quantity: _Quantity, unit: Unit, - expected: Quantity, + expected: _Quantity, ) -> None: result = quantity.convert_to(unit) @@ -729,7 +729,7 @@ def test_quantity_convert_same_absolute_unit_returns_self() -> None: ), ) def test_quantity_convert_to_dimensionality_error_if_units_not_dimensionally_consistent( - quantity: Quantity, + quantity: _Quantity, unit: Unit, ) -> None: with pytest.raises( @@ -749,7 +749,7 @@ def test_quantity_convert_to_dimensionality_error_if_units_not_dimensionally_con (1.0 * (kilogram * co2) / (kilogram * nox), UNITLESS), ), ) - def test_quantity_convert_to_dimensionality_error_if_tags_differ(quantity: Quantity, unit: Unit) -> None: + def test_quantity_convert_to_dimensionality_error_if_tags_differ(quantity: _Quantity, unit: Unit) -> None: with pytest.raises(BiltDimensionalityError, match="Cannot convert"): quantity.convert_to(unit) @@ -791,7 +791,7 @@ def test_quantity_convert_to_unit_error_if_converting_absolute_to_relative() -> ), ) def test_strip_metadata( - quantity: Quantity, - expected: Quantity, + quantity: _Quantity, + expected: _Quantity, ) -> None: assert quantity.strip_metadata() == expected diff --git a/tests/units/test_units.py b/tests/units/test_units.py index cb83a389..0b68aa52 100644 --- a/tests/units/test_units.py +++ b/tests/units/test_units.py @@ -47,12 +47,10 @@ ) from bilt.units._metadata import Metadata from bilt.units._prefix import Prefix +from bilt.units._quantities import _Quantity from bilt.units._units import BASE_UNIT_SYSTEM, Unit, UnitComposition, UnitOrder from bilt.units.dimensions._dimensions import DIMENSIONLESS, LENGTH, MASS, TEMPERATURE, TIME, Dimension -if typing.TYPE_CHECKING: - from bilt.units._quantities import Quantity - electric = Metadata("electric") thermal = Metadata("thermal") @@ -827,7 +825,7 @@ class TestDimensionless: ("count", UNITLESS, UnitComposition()), ), ) - def test_new_named(name: str, relation: Unit | Quantity, expected_relation: UnitComposition) -> None: + def test_new_named(name: str, relation: Unit | _Quantity, expected_relation: UnitComposition) -> None: unit = Unit.new_named(name, relation) assert unit.name == name assert unit.relation == expected_relation @@ -958,7 +956,7 @@ def test_unit_error_if_reinstantiation_with_different_scale() -> None: (1.0 * celsius, 1.0 * celsius, 2.0 * celsius), ), ) - def test_addition(left: Quantity, right: Quantity, expected: Quantity) -> None: + def test_addition(left: _Quantity, right: _Quantity, expected: _Quantity) -> None: assert (left + right) == expected @staticmethod @@ -971,7 +969,7 @@ def test_addition(left: Quantity, right: Quantity, expected: Quantity) -> None: (1.0 * abs(fahrenheit), 1.0 * abs(fahrenheit)), ), ) - def test_unit_error_for_addition_of_two_absolute_units(left: Quantity, right: Quantity) -> None: + def test_unit_error_for_addition_of_two_absolute_units(left: _Quantity, right: _Quantity) -> None: message = "Cannot add two quantities with absolute units of .* and .*" with pytest.raises(BiltUnitError, match=message): _ = left + right @@ -993,7 +991,7 @@ def test_unit_error_for_addition_of_two_absolute_units(left: Quantity, right: Qu (100.0 * abs(fahrenheit), abs(celsius), 340 / 9 * abs(celsius)), ), ) - def test_convert_to(quantity: Quantity, unit: Unit, expected: Quantity) -> None: + def test_convert_to(quantity: _Quantity, unit: Unit, expected: _Quantity) -> None: result = quantity.convert_to(unit) assert result.value == pytest.approx(expected.value) @@ -1039,18 +1037,20 @@ def test_is_relative(unit: Unit, expected: bool) -> None: (20.0 * celsius, 20.0), ), ) - def test_coherent_value_counts_an_absolute_quantity_from_absolute_zero(quantity: Quantity, expected: float) -> None: + def test_coherent_value_counts_an_absolute_quantity_from_absolute_zero( + quantity: _Quantity, expected: float + ) -> None: assert BASE_UNIT_SYSTEM.coherent_value(quantity) == pytest.approx(expected) @staticmethod def test_coherent_value_unit_error_if_unit_compounds_an_absolute_unit() -> None: with pytest.raises(BiltUnitError, match="compound unit containing an absolute unit"): - BASE_UNIT_SYSTEM.coherent_value(60.0 * kilogram * absolute_celsius) + BASE_UNIT_SYSTEM.coherent_value(_Quantity(60.0, kilogram * absolute_celsius)) @staticmethod def test_coherent_value_unit_error_if_coherent_unit_has_no_absolute_counterpart() -> None: with pytest.raises(BiltUnitError, match="No absolute unit corresponding to second exists"): - BASE_UNIT_SYSTEM.coherent_value(2020.0 * absolute_year) + BASE_UNIT_SYSTEM.coherent_value(_Quantity(2020.0, absolute_year)) class TestTaggedUnit: @@ -1107,7 +1107,7 @@ def test_coherent_unit_keeps_each_tag(dimension: Dimension, expected: Unit) -> N (50.0 * percent * co2, 0.5), ), ) - def test_coherent_value_converts_within_the_tagged_dimension(quantity: Quantity, expected: float) -> None: + def test_coherent_value_converts_within_the_tagged_dimension(quantity: _Quantity, expected: float) -> None: assert BASE_UNIT_SYSTEM.coherent_value(quantity) == pytest.approx(expected) @staticmethod @@ -1121,7 +1121,7 @@ def test_coherent_value_converts_within_the_tagged_dimension(quantity: Quantity, ), ) def test_named_unit_keeps_each_tag_of_its_relation( - name: str, relation: Unit | Quantity, expected: Dimension + name: str, relation: Unit | _Quantity, expected: Dimension ) -> None: assert Unit.new_named(name, relation).dimension is expected @@ -1135,7 +1135,7 @@ def test_named_unit_keeps_each_tag_of_its_relation( ), ) def test_named_unit_converts_back_to_its_tagged_relation( - name: str, relation: Unit | Quantity, expected: float + name: str, relation: Unit | _Quantity, expected: float ) -> None: converted = (1.0 * Unit.new_named(name, relation)).convert_to(kilogram * co2) assert converted.unit is kilogram * co2