lair.inventories.convert_units#

lair.inventories.convert_units(data, pollutant, dst_units)[source]#

Convert the units of a data array or dataset.

The data either has pint units (.pint.quantify(), what an Inventory holds) or is plain, with a units attribute. It comes back the same way: pint units in, pint units out; plain in, plain out, with the units attribute and the values converted and everything else (name, coordinates and their attributes, other attributes) as it was. A conversion between an amount (mol) and a mass (kg) uses the molecular weight of pollutant, through the mass_flux pint context.

The data has no time steps here, so a flux per year is per pint’s year of 365.25 days, and a flux per month per a twelfth of it. Inventory.convert_units() gives a flux per year on annual data the length of each year instead (366 days in a leap year), and a flux per month on monthly data the length of each month.

Parameters:
  • data (xr.DataArray | xr.Dataset) – The data to convert. A dataset converts every variable, so each needs units.

  • pollutant (str) – The pollutant, as a chemical formula (see molecular_weight()).

  • dst_units (Any) – The destination units.

Returns:

xr.DataArray | xr.Dataset – The data with converted units. data itself is not changed.

Raises:
  • TypeError – If data is not an xarray DataArray or Dataset.

  • ValueError – If plain data has no units attribute.

Return type:

_XarrayT

See also

Inventory.convert_units

The same for an inventory’s data, with the calendar length of each time step.

molecular_weight

The molecular weight the conversion uses.

Examples

A grid of methane fluxes read from a file, in nmol m-2 s-1, to kg km-2 d-1:

>>> import xarray as xr
>>> from lair.inventories import convert_units
>>> flux = xr.DataArray(
...     [[10.0, 20.0], [30.0, 40.0]],
...     dims=("y", "x"),
...     attrs={"units": "nmol m-2 s-1"},
... )
>>> kg = convert_units(flux, "CH4", "kg km-2 d-1")
>>> kg.attrs["units"]
'kg km-2 d-1'
>>> round(float(kg[0, 0]), 2)
13.86

A flux per year is per pint’s year of 365.25 days:

>>> per_second = xr.DataArray([1.0], dims="x", attrs={"units": "kg m-2 s-1"})
>>> per_year = convert_units(per_second, "CH4", "kg m-2 yr-1")
>>> float(per_year[0]) / 86400  # days
365.25