src.units module

Functions wrapping unit conversion methods from the third-party cfunits library.

src.units.to_cfunits(*args)[source]

Coerce string-valued units and (quantity, unit) tuples to Units objects.

If more than one such argument is given in args, return a list containing the results of coercing each argument.

src.units.to_equivalent_units(*args)[source]

Same as to_cfunits(), but raises TypeError if units of all quantities in args are not equivalent after coercion.

src.units.relative_tol(x, y)[source]

HACK to return max(|x-y|/x, |x-y|/y) for unit-ful quantities x, y with equivalent units. Vulnerable to underflow in principle.

x and y are coerced to Units objects via to_cfunits().

src.units.units_equivalent(*args)[source]

Returns True if and only if all unit-ful quantities in args are physically equivalent: they represent the same physical quantity, up to a multiplicative conversion factor.

args are coerced to Units objects via to_cfunits().

src.units.units_reftime_base_eq(*args)[source]

Returns True if and only if all unit-ful quantities in args are physically equivalent: they represent the same physical quantity, up to a multiplicative conversion factor.

args are coerced to Units objects via to_cfunits().

src.units.units_equal(*args, rtol=None)[source]

Returns True if and only if all unit-ful quantities in args are strictly equal (units_equivalent() is True and conversion_factor() = 1).

Note

rtol, atol tolerances on floating-point equality are not currently implemented in cfunits, so we use relative_tol().

args are coerced to Units objects via to_cfunits().

src.units.conversion_factor(source_unit, dest_unit)[source]

Return floating point factor which implements a given unit conversion. Defined so that (conversion factor) * (quantity in source_units) = (quantity in dest_units).

source_unit, dest_unit are coerced to Units objects via to_cfunits().

src.units.convert_scalar_coord(coord, dest_units, log=<Logger>)[source]

Given scalar coordinate coord, return the appropriate scalar value in new units dest_units.

src.units.convert_dataarray(ds, da_name, src_unit=None, dest_unit=None, log=<Logger>)[source]

Wrapper for cfunits conform() that does unit conversion in-place on a member of an xarray Dataset, updating its units attribute.

Parameters
  • ds (Dataset) – xarray Dataset containing the DataArray to convert.

  • da_name (str) – Name of the DataArray to do the unit conversion on.

  • src_unit – Current units of da_name. Coerced to a Units object via to_cfunits(). Optional; if not given this is populated from the units attribute of da_name, if it exists.

  • dest_unit – Desired units for da_name. Coerced to a Units object via to_cfunits().

Raises
  • ValueError – if da_name not in ds.

  • TypeError – if src_unit or dest_unit not correctly defined, or if da_name lacks units metadata.

Returns

Dataset ds, with da_name modified in-place.