Quantity#

class ansys.units.quantity.Quantity(value: float | _ArrayInput | None = None, units: Unit | str | None = None, *, quantity_table: Mapping[QuantityKey, float] | None = None, dimensions: Dimensions | None = None, copy_from: Quantity | None = None, **kwargs: Any)#

Bases: Generic[ValT]

A class representing a physical quantity’s value and associated units.

A Quantity object can be instantiated from a NumPy array or list only if the NumPy package is installed.

The value argument is not required when using copy_from. A value can be given to override the value from the copy.

Implicit conversion from Quantity to float is only allowed if the operand is of quantity type angle or dimensionless.

Parameters:
valueint, float, list, np.array

Real value of the quantity.

unitsstr, Unit, optional

Initializes the quantity’s units using a string or Unit instance.

quantity_tabledict[str, int], optional

Initializes the quantity’s units using the quantity table.

dimensionsDimensions, optional

Initializes the quantity’s units in SI using a Dimensions instance.

copy_fromQuantity, optional

An existing Quantity instance.

Attributes:
value

Value in contained units.

units

The quantity’s units.

dimensions

The quantity’s dimensions.

is_dimensionless

True if the quantity is dimensionless.

compatible_units() → set[str]#

Get all units with the same dimensions.

Returns:
set

A set of unit objects.

convert(system: UnitSystem, preferred_units: PreferredUnits | Sequence[Literal['kg', 'g', 'lb', 'lbm', 'slug', 'm', 'cm', 'ft', 'inch', 'in', 's', 'A', 'mol', 'slugmol', 'cd', 'sr', 'radian', 'degree', 'rev', 'K', 'C', 'F', 'R', 'delta_K', 'delta_C', 'delta_F', 'delta_R', 'min', 'h', 'N', 'Pa', 'bar', 'W', 'J', 'V', 'farad', 'H', 'S', 'Wb', 'T', 'dyne', 'erg', 'pdl', 'psi', 'lbf', 'psf', 'ohm', 'Hz', 'l', 'gal', 'BTU', 'cal', 'coulomb', 'tonne'] | str | UnitLike] | Literal['kg', 'g', 'lb', 'lbm', 'slug', 'm', 'cm', 'ft', 'inch', 'in', 's', 'A', 'mol', 'slugmol', 'cd', 'sr', 'radian', 'degree', 'rev', 'K', 'C', 'F', 'R', 'delta_K', 'delta_C', 'delta_F', 'delta_R', 'min', 'h', 'N', 'Pa', 'bar', 'W', 'J', 'V', 'farad', 'H', 'S', 'Wb', 'T', 'dyne', 'erg', 'pdl', 'psi', 'lbf', 'psf', 'ohm', 'Hz', 'l', 'gal', 'BTU', 'cal', 'coulomb', 'tonne'] | str | UnitLike | None = None) → Quantity#

Convert a quantity into the unit system.

Parameters:
systemUnitSystem

Unit system to convert to.

preferred_unitsPreferredUnits, optional

Conversion policy deciding which named derived unit to emit for matching dimensions, instead of the expanded base-unit expression. A plain unit or sequence of units is wrapped in a PreferredUnits automatically.

Returns:
Quantity

Quantity object converted into the unit system.

Examples

>>> ur = UnitRegistry()
>>> speed_si = Quantity(value=5, units= ur.m / ur.s)
>>> bt = UnitSystem(system="BT")
>>> speed_bt = speed_si.convert(bt)
property dimensions: Dimensions#

The quantity’s dimensions.

classmethod from_dict(data: Mapping[str, Any], registry: UnitRegistry | None = None) → Quantity#

Create a quantity from a dictionary written by to_dict().

Parameters:
datadict

Serialized quantity. Keys other than "value", "units" and "unit_definition" become extra fields.

registryUnitRegistry, optional

Registry used to resolve the unit name. Defaults to the application registry (see set_application_registry()).

classmethod from_string(text: str, registry: UnitRegistry | None = None) → Quantity#

Parse a quantity from its string representation.

Accepts the output of str(quantity), such as "5.0 m s^-1" or "[1. 2. 3.] kg". Summarized NumPy output (containing ...) cannot be parsed.

Parameters:
textstr

String representation.

registryUnitRegistry, optional

Registry used to resolve the unit name.

Examples

>>> Quantity.from_string("5.0 m s^-1")
Quantity(5.0, "m s^-1")
property is_dimensionless: bool#

True if the quantity is dimensionless.

property ndim: int#

Number of dimensions of the quantity’s value.

classmethod preferred_units(units: Sequence[Unit | Literal['kg', 'g', 'lb', 'lbm', 'slug', 'm', 'cm', 'ft', 'inch', 'in', 's', 'A', 'mol', 'slugmol', 'cd', 'sr', 'radian', 'degree', 'rev', 'K', 'C', 'F', 'R', 'delta_K', 'delta_C', 'delta_F', 'delta_R', 'min', 'h', 'N', 'Pa', 'bar', 'W', 'J', 'V', 'farad', 'H', 'S', 'Wb', 'T', 'dyne', 'erg', 'pdl', 'psi', 'lbf', 'psf', 'ohm', 'Hz', 'l', 'gal', 'BTU', 'cal', 'coulomb', 'tonne']], remove: bool = False) → None#

Add or remove preferred units.

Quantities are automatically converted to preferred units when the quantity is initialized. Conversion is always carried out if the base units are consistent with the preferred units.

Each preferred unit must have unique dimensions. To override units with the same dimensions, the original must first be removed.

Parameters:
unitslist

A list of units to be added or removed.

removebool

Specify if the units should be removed.

property shape: tuple[int, ...]#

Shape of the quantity’s value (() for a scalar).

property size: int#

Number of elements in the quantity’s value.

to(to_units: Unit | str) → Quantity[ValT]#

Perform quantity conversions.

Parameters:
to_unitsUnit or str

Desired unit to convert to.

Returns:
Quantity

Quantity instance in the desired units.

Examples

>>> speed_si = Quantity(value=5, units="m s^-1")
>>> speed_bt = speed_si.to("ft s^-1")
to_dict() → dict[str, Any]#

Serialize the quantity to a dictionary of built-in Python types.

The dictionary contains "value" (a float, or nested lists for arrays), "units" (the unit name), and any extra fields given to the constructor. Custom units that are only defined in a UnitRegistry also include a "unit_definition".

This is the format used by the pydantic integration. For JSON, use a pydantic model (or pydantic.TypeAdapter(Quantity)), or json.dumps(quantity.to_dict()) without pydantic. Pydantic writes NaN and infinity as null by default; set model_config = ConfigDict(ser_json_inf_nan="constants") to keep them.

Examples

>>> Quantity(5, "m s^-1").to_dict()
{'value': 5.0, 'units': 'm s^-1'}
property units: Unit#

The quantity’s units.

validate_matching_dimensions(other: object) → None#

Validates dimensions of quantities.

property value: ValT#

Value in contained units.

ansys.units.quantity.get_si_value(quantity: Quantity[ValT]) → ValT#

Returns a quantity’s value in SI units.

exception ansys.units.quantity.ExcessiveParameters#

Bases: ValueError

Raised when excessive parameters are provided.

exception ansys.units.quantity.IncompatibleDimensions(from_unit: Unit, to_unit: Unit)#

Bases: ValueError

Raised when dimensions are incompatible.

exception ansys.units.quantity.IncompatibleQuantities(q1: object, q2: object)#

Bases: ValueError

Raised when quantities are incompatible.

exception ansys.units.quantity.IncompatibleValue(value: object)#

Bases: ValueError

Raised when an incompatible value is provided.

exception ansys.units.quantity.InsufficientArguments#

Bases: ValueError

Raised when insufficient arguments are provided.

exception ansys.units.quantity.InvalidFloatUsage#

Bases: FloatingPointError

Raised when float is unsupported for given type of quantity.

exception ansys.units.quantity.NumPyRequired#

Bases: ModuleNotFoundError

Raised when NumPy is unavailable.

exception ansys.units.quantity.DimensionlessArgumentRequired(function_name: str, units: Unit, angle: bool = False)#

Bases: ValueError

Raised when a NumPy function requires a dimensionless (or angle) argument.

exception ansys.units.quantity.RequiresUniqueDimensions(unit: Unit, other_unit: Unit)#

Bases: ValueError

Raised when two units with the same dimensions are added to the chosen units.