From a869dc7724174ef5725ae84caea92d307a739694 Mon Sep 17 00:00:00 2001 From: veenstrajelmer <60435591+veenstrajelmer@users.noreply.github.com> Date: Fri, 16 Aug 2024 20:31:50 +0200 Subject: [PATCH] properly adding attrs after applying conversion from conversion_dict (#965) * properly adding attrs after applying conversion from conversion_dict * updated whatsnew * improved test --- dfm_tools/interpolate_grid2bnd.py | 8 +++++--- docs/whats-new.md | 6 ++++++ tests/test_interpolate_grid2bnd.py | 1 + 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/dfm_tools/interpolate_grid2bnd.py b/dfm_tools/interpolate_grid2bnd.py index f4e03a06a..a30c8eae4 100644 --- a/dfm_tools/interpolate_grid2bnd.py +++ b/dfm_tools/interpolate_grid2bnd.py @@ -354,9 +354,11 @@ def ds_apply_conversion_dict(data_xr, conversion_dict, quantity): # TODO: maybe do unit conversion before interp or is that computationally heavy? if 'conversion' in conversion_dict[quantity].keys(): #if conversion is present, unit key must also be in conversion_dict print(f'> converting units from [{data_xr[quantity].attrs["units"]}] to [{conversion_dict[quantity]["unit"]}]') - #print(f'attrs are discarded:\n{data_xr_vars[quan].attrs}') - data_xr[quantity] = data_xr[quantity] * conversion_dict[quantity]['conversion'] #conversion drops all attributes of which units (which are changed anyway) - data_xr[quantity].attrs['units'] = conversion_dict[quantity]['unit'] #add unit attribute with resulting unit + # conversion drops all attributes of which units (which are changed anyway) + data_xr[quantity] = data_xr[quantity] * conversion_dict[quantity]['conversion'] + # add unit attribute with resulting unit + quantity_attrs = {'units': conversion_dict[quantity]['unit']} + data_xr[quantity] = data_xr[quantity].assign_attrs(quantity_attrs) return data_xr diff --git a/docs/whats-new.md b/docs/whats-new.md index 7c4e91c56..bf43d8de9 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,11 @@ # What's new +## UNRELEASED + +### Fix +- properly assigning units attribute in `ds_apply_conversion_dict()` (it did not always stick) in [#965](https://github.com/Deltares/dfm_tools/pull/965) + + ## 0.25.0 (2024-08-16) ### Feat diff --git a/tests/test_interpolate_grid2bnd.py b/tests/test_interpolate_grid2bnd.py index 3ddfcdcf0..d9ea114b5 100644 --- a/tests/test_interpolate_grid2bnd.py +++ b/tests/test_interpolate_grid2bnd.py @@ -300,6 +300,7 @@ def test_ds_apply_conversion_dict_rename_and_factor(): assert 'o2' in ds_moretime.data_vars assert 'tracerbndOXY' in ds_converted.data_vars assert np.allclose(ds_converted['tracerbndOXY'], ds_moretime['o2']*0.032, equal_nan=True) + assert ds_converted['tracerbndOXY'].attrs['units'] == 'g/m3' @pytest.mark.unittest