Skip to content

Commit

Permalink
code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
siligam committed Jul 22, 2024
1 parent f9d8264 commit 9bb9e59
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 16 deletions.
15 changes: 9 additions & 6 deletions src/pymorize/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,13 @@
ureg = pint_xarray.unit_registry


def handle_chemicals(s: str, pattern: Pattern = re.compile(r"mol(?P<symbol>\w+)")):
def handle_chemicals(
s: str | None = None, pattern: Pattern = re.compile(r"mol(?P<symbol>\w+)")
):
"""Registers known chemical elements definitions to global ureg (unit registry)"""
try:
match = pattern.search(s)
except TypeError:
if s is None:
return
match = pattern.search(s)
if match:
d = match.groupdict()
try:
Expand All @@ -46,7 +47,9 @@ def handle_chemicals(s: str, pattern: Pattern = re.compile(r"mol(?P<symbol>\w+)"
ureg.define(f"{match.group()} = {element.MW} * g")


def handle_unit_conversion(da: xr.DataArray, unit: str, source_unit: str = None) -> xr.DataArray:
def handle_unit_conversion(
da: xr.DataArray, unit: str, source_unit: str | None = None
) -> xr.DataArray:
"""Performs the unit-aware data conversion.
If `source_unit` is provided, it is used instead of the unit from DataArray.
Expand All @@ -58,7 +61,7 @@ def handle_unit_conversion(da: xr.DataArray, unit: str, source_unit: str = None)
source_unit: Override the unit on xr.DataArray if needed.
"""
from_unit = da.attrs.get("units")
if source_unit:
if source_unit is not None:
logger.debug(
f"using user defined unit ({source_unit}) instead of ({from_unit}) from DataArray "
)
Expand Down
13 changes: 3 additions & 10 deletions tests/test_units.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
import numpy as np
import pint
import pytest

# import cf_xarray.units
# import pint_xarray
import xarray as xr
import pint
import numpy as np
from chemicals import periodic_table
from pymorize.units import (
handle_unit_conversion,
ureg,
handle_chemicals,
)

from pymorize.units import handle_chemicals, handle_unit_conversion, ureg

# input samples that are found in CMIP6 tables and in fesom1 (recom)
allunits = [
Expand Down

0 comments on commit 9bb9e59

Please sign in to comment.