Skip to content

units_converter

Classes:

Name Description
UnitsConverter

Converts the units of a retrieved variable to specified output units.

Classes#

UnitsConverter #

Bases: DataConverter

Converts the units of a retrieved variable to specified output units.

If the 'input_units' property is set then that string is used to determine the input input units, otherwise the converter will attempt to look up and use the 'units' attribute on the specified variable in the dataset provided to the convert method. If the input units cannot be set then a warning is issued and the original dataset is returned. The output units are specified by the output dataset configuration.

Methods:

Name Description
convert

Attributes:

Name Type Description
input_units Optional[str]

The units of the input data.

Attributes#

input_units class-attribute instance-attribute #
input_units: Optional[str] = None

The units of the input data.

Functions#

convert #
convert(
    data: xr.DataArray,
    variable_name: str,
    dataset_config: DatasetConfig,
    retrieved_dataset: RetrievedDataset,
    **kwargs: Any
) -> Optional[xr.DataArray]
Source code in tsdat/io/converters/units_converter.py
def convert(
    self,
    data: xr.DataArray,
    variable_name: str,
    dataset_config: DatasetConfig,
    retrieved_dataset: RetrievedDataset,
    **kwargs: Any,
) -> Optional[xr.DataArray]:
    # Can only convert number-like dtypes (not strings, datetimes, objects)
    if not pd.api.types.is_any_real_numeric_dtype(data.data):
        return None

    output_units = self._get_output_units(dataset_config[variable_name])
    if output_units is None:
        return None

    input_units = self._get_input_units(data, variable_name)
    if (
        (not input_units)
        or (input_units == "1")
        or (output_units == "1")
        or (input_units == output_units)
    ):
        data_array = data.copy().astype(dataset_config[variable_name].dtype)
        data_array.attrs["units"] = dataset_config[variable_name].attrs.units
        return data_array

    try:
        # Run pint and set output data
        out_dtype = dataset_config[variable_name].dtype
        converted = (data.data * ureg(input_units)).to(output_units).magnitude
        data_array = data.copy(data=converted.astype(out_dtype))
    except AttributeError:
        print(f"the what??? {data=}, {ureg(input_units)=}, {output_units=}")
        raise

    # Use original output units text
    data_array.attrs["units"] = dataset_config[variable_name].attrs.units
    logger.debug(
        "Converted '%s's units from '%s' to '%s'",
        variable_name,
        input_units,
        output_units,
    )
    return data_array

Functions#