Coverage for tcvx21/units_m.py: 100%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2Set up the "Pint" unit library
4See unit_registry.txt for defined units (for reference only)
5"""
6import pint
7import os
8import warnings
9import xarray as xr
10import numpy as np
12# Disable Pint's old fallback behavior (must come before importing Pint)
13# Ignore pylint warning C0413: Import "import pint" should be placed at
14# the top of the module
15os.environ['PINT_ARRAY_PROTOCOL_FALLBACK'] = "0"
17unit_registry = pint.UnitRegistry()
18Quantity = unit_registry.Quantity
19Dimensionless = Quantity(1, "")
21# Silence NEP 18 warning
22with warnings.catch_warnings():
23 warnings.simplefilter("ignore")
24 Quantity([])
26unit_registry.setup_matplotlib()
28# Hide a warning that units are stripped when downcasting to numpy arrays
29warnings.simplefilter('ignore', category=pint.errors.UnitStrippedWarning)
32def convert_xarray_to_quantity(input_array: xr.DataArray) -> Quantity:
33 """
34 Converts an xarray with units attribute into a pint.Quantity with units (useful for unit checking)
36 If the base array is already a Quantity, its units will be silently overwritten
38 Note that all attributes except units will be lost.
39 Not recommended except as a sanity check/in tests
40 """
41 with warnings.catch_warnings():
42 warnings.simplefilter('ignore', category=pint.errors.UnitStrippedWarning)
43 return input_array.norm * np.asarray(input_array)