ensure_quantity

openff.units.openmm.ensure_quantity(unknown_quantity: Union[Quantity, openmm_unit.Quantity], type_to_ensure: Literal['openmm', 'openff']) Union[Quantity, openmm_unit.Quantity][source]

Given a quantity that could be of a variety of types, attempt to coerce into a given type.

Examples

>>> import numpy
>>> from openmm import unit as openmm_unit
>>> from openff.units import unit
>>> from openff.units.openmm import ensure_quantity
>>> # Create a 9 Angstrom quantity with each registry
>>> length1 = unit.Quantity(9.0, unit.angstrom)
>>> length2 = openmm_unit.Quantity(9.0, openmm_unit.angstrom)
>>> # Similar quantities are be coerced into requested type
>>> assert type(ensure_quantity(length1, "openmm")) == openmm_unit.Quantity
>>> assert type(ensure_quantity(length2, "openff")) == unit.Quantity
>>> # Seemingly-redundant "conversions" short-circuit
>>> assert ensure_quantity(length1, "openff") == ensure_quantity(length2, "openff")
>>> assert ensure_quantity(length1, "openmm") == ensure_quantity(length2, "openmm")
>>> # NumPy arrays and some primitives are automatically up-converted to `Quantity` objects
>>> # Note that their units are set to "dimensionless"
>>> ensure_quantity(numpy.array([1, 2]), "openff")
<Quantity([1 2], 'dimensionless')>
>>> ensure_quantity(4.0, "openmm")
Quantity(value=4.0, unit=dimensionless)