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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions si-units/docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
- cbrt
- sqrt
- has_unit
- value_in
summary:
attributes: false
functions: true
Expand Down
7 changes: 7 additions & 0 deletions si-units/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,13 @@ impl PySIObject {
self.unit.eq(&other.unit)
}

pub fn value_in<'py>(&self, py: Python<'py>, unit: &Self) -> PyResult<Bound<'py, PyAny>> {
self.check_units(unit)?;
self.value
.bind(py)
.call_method1("__truediv__", (&unit.value,))
}

#[classattr]
fn __array_priority__() -> u64 {
1000
Expand Down
31 changes: 27 additions & 4 deletions si-units/src/si_units/_core.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Self, Any
from typing import Any, Self

class SIObject:
"""Combination of value and unit.
Expand All @@ -14,7 +14,7 @@ class SIObject:
def __init__(self, value: float | Any, unit: list[int]) -> None:
"""Constructs a new quantity.

Warning: Don't use the default constructor
Warning: Don't use the default constructor
This constructor should not be used to construct a quantity.
Instead, multiply the value (float or array of floats)
by the appropriate unit. See example below.
Expand Down Expand Up @@ -64,7 +64,7 @@ class SIObject:
Raises:
RuntimeError: When exponents of units are not multiples of three.
AttributeError: When the inner data type has no 'cbrt' method.

Examples:
>>> from si_units import METER
>>> volume = METER**3
Expand All @@ -83,6 +83,29 @@ class SIObject:
"""
...

def value_in(self, unit: Self) -> float | Any:
"""Return the numeric value expressed in specified unit.

The underlying value (float, numpy.ndarray, torch.tensor, ...)
is divided by unit and returned without the unit wrapper.

Args:
unit: A quantity describing target unit (e.g. KILO * WATT * HOUR).

Returns:
The numeric value of self expressed in unit.

Raises:
RuntimeError: When self and unit have incompatible units.

Examples:
>>> from si_units import JOULE, KILO, WATT, HOUR
>>> energy = 5.4e6 * JOULE
>>> energy.value_in(KILO * WATT * HOUR)
1.5
"""
...

def array(value: SIObject | list[SIObject]) -> SIObject:
"""Build SIObject from scalar or list.

Expand All @@ -92,7 +115,7 @@ def array(value: SIObject | list[SIObject]) -> SIObject:
value: Values to store. Must all have the same unit.

Returns:
The quantity with values stored within array,
The quantity with values stored within array,
even if value is given as a scalar.

Raises:
Expand Down
Loading