Skip to content

Commit

Permalink
raising error on wrong normalization task
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasprobst committed Nov 30, 2023
1 parent bed9c4b commit 9201f13
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
13 changes: 11 additions & 2 deletions h5rdmtoolbox/extensions/normalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

import h5rdmtoolbox as h5tbx

from numpy.core._exceptions import _UFuncBinaryResolutionError


def to_base_units(da: xr.DataArray) -> xr.DataArray:
"""Turns the units of an xarray to the base units, e.g. m/mm turns to dimensionless
Expand Down Expand Up @@ -39,11 +41,18 @@ def _normalize(obj, name, value, rename):
if isinstance(value, str):
qobj = obj.pint.quantify(unit_registry=h5tbx.get_ureg())
q = h5tbx.get_ureg()(value)
norm_obj = (qobj/q).pint.dequantify()
norm_obj = (qobj / q).pint.dequantify()
elif isinstance(value, (int, float)):
# user indicates a float or int, which is interpreted as dimensionless
with xr.set_options(keep_attrs=True):
norm_obj = obj / value
try:
norm_obj = obj / value
except _UFuncBinaryResolutionError:
raise RuntimeError(f'A error occurred while normalizing {obj.name} by {name}={value}. '
'This is likely due to a mismatch of data types. '
'you might specify the dimension to be normalized by '
'because not every dimension might of of a numeric type. '
'Orig. error: {e}')
else:
raise TypeError(f'Normalization must be either a string or a float, not {type(v)}.')

Expand Down
16 changes: 16 additions & 0 deletions tests/test_extensions.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import datetime
import numpy as np
import unittest
import xarray as xr
Expand Down Expand Up @@ -62,6 +63,21 @@ def test_Vector(self):
self.assertEqual(vec2.attrs['test'], 1)
self.assertIsInstance(vec2, xr.DataArray)

def test_normalize_issue_with_time_vector(self):
with h5tbx.File() as h5:
h5.create_dataset('x', data=[1, 2, 3], make_scale=True)
now = datetime.datetime.now()
h5.create_time_dataset('t',
data=[now, now + datetime.timedelta(seconds=1), now + datetime.timedelta(seconds=2)],
make_scale=True)
u = h5.create_dataset('u', data=[-4, 10, 0], attach_scales=[('t', 'x'), ])

with self.assertRaises(RuntimeError):
u[()].normalize.coords(rename=True, L=5)
unorm = u[()].normalize.coords(rename=True, x=dict(L=5))
np.testing.assert_array_equal(unorm.x.values, u[()].x.values / 5)
np.testing.assert_array_equal(unorm.values, u[()].values)

def test_norm_one_for_all_without_unit(self):
with h5tbx.File() as h5:
h5.create_dataset('x', data=[1, 2, 3], make_scale=True)
Expand Down

0 comments on commit 9201f13

Please sign in to comment.