Skip to content

Commit

Permalink
Try to read event coordinate as date
Browse files Browse the repository at this point in the history
  • Loading branch information
peanutfun committed Jan 15, 2024
1 parent 725a291 commit c8d5b7f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
24 changes: 23 additions & 1 deletion climada/hazard/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,24 @@ def date_to_ordinal_accessor(
)
return np.zeros(array.shape)

def year_month_day_accessor(
array: xr.DataArray, strict: bool = True
) -> np.ndarray:
"""Take an array and return am array of YYYY-MM-DD strings"""
try:
return array.dt.strftime("%Y-%m-%d").values

# Handle access errors
except (ValueError, TypeError) as err:
if strict:
raise err

LOGGER.warning(

Check warning on line 841 in climada/hazard/base.py

View check run for this annotation

Jenkins - WCR / Pylint

logging-not-lazy

NORMAL: Use lazy % formatting in logging functions
Raw output
Used when a logging statement has a call form of "logging.<loggingmethod>(format_string % (format_args...))". Such calls should leave stringinterpolation to the logging method itself and be written "logging.<loggingmethod>(format_string, format_args...)" so that the program may avoidincurring the cost of the interpolation in those cases in which no messagewill be logged. For more, see http://www.python.org/dev/peps/pep-0282/.
"Failed to read values of '%s' as dates. Hazard.event_name will be "
"empty strings" % array.name
)
return np.full(array.shape, "")

def maybe_repeat(values: np.ndarray, times: int) -> np.ndarray:
"""Return the array or repeat a single-valued array
Expand Down Expand Up @@ -855,7 +873,11 @@ def maybe_repeat(values: np.ndarray, times: int) -> np.ndarray:
None,
np.ones(num_events),
np.array(range(num_events), dtype=int) + 1,
[""] * num_events,
list(
year_month_day_accessor(
data[coords["event"]], strict=False
).flat
),
date_to_ordinal_accessor(data[coords["event"]], strict=False),
],
# The accessor for the data in the Dataset
Expand Down
21 changes: 15 additions & 6 deletions climada/hazard/test/test_base_xarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,8 @@ def _assert_default_values(self, hazard):
self.assertEqual(hazard.haz_type, "")
self.assertEqual(hazard.units, "")
np.testing.assert_array_equal(hazard.event_id, [1, 2])
np.testing.assert_array_equal(hazard.event_name, ["", ""])
np.testing.assert_array_equal(
hazard.date, [val.toordinal() for val in self.time]
hazard.event_name, [x.strftime("%Y-%m-%d") for x in self.time]
)
np.testing.assert_array_equal(hazard.frequency, np.ones(hazard.event_id.size))

Expand Down Expand Up @@ -177,8 +176,12 @@ def test_event_no_time(self):
with self.assertLogs("climada.hazard.base", "WARNING") as cm:
hazard = Hazard.from_xarray_raster(dataset, "", "")
np.testing.assert_array_equal(hazard.date, np.zeros(size))
np.testing.assert_array_equal(hazard.event_name, np.full(size, ""))
self.assertIn(
"Failed to read values of 'time' as dates.", cm.output[0]
)
self.assertIn(
"Failed to read values of 'time' as dates or ordinals.", cm.output[0]
"Failed to read values of 'time' as dates or ordinals.", cm.output[1]
)

def test_data_vars(self):
Expand Down Expand Up @@ -361,7 +364,9 @@ def test_missing_dims(self):
ds = ds.isel(time=0).squeeze()
hazard = Hazard.from_xarray_raster(ds, "", "")
self._assert_default_types(hazard)
np.testing.assert_array_equal(hazard.event_name, [""])
np.testing.assert_array_equal(
hazard.event_name, [self.time[0].strftime("%Y-%m-%d")]
)
np.testing.assert_array_equal(hazard.date, [self.time[0].toordinal()])
np.testing.assert_array_equal(hazard.centroids.lat, [0, 0, 0, 1, 1, 1])
np.testing.assert_array_equal(hazard.centroids.lon, [0, 1, 2, 0, 1, 2])
Expand All @@ -383,7 +388,9 @@ def test_missing_dims(self):
ds = ds.expand_dims(time=[np.datetime64("2022-01-01")])
hazard = Hazard.from_xarray_raster(ds, "", "")
self._assert_default_types(hazard)
np.testing.assert_array_equal(hazard.event_name, [""])
np.testing.assert_array_equal(
hazard.event_name, ["2022-01-01"]
)
np.testing.assert_array_equal(
hazard.date, [dt.datetime(2022, 1, 1).toordinal()]
)
Expand Down Expand Up @@ -563,7 +570,9 @@ def test_2D_time(self):
np.testing.assert_array_equal(
hazard.date, [val.toordinal() for val in time.flat]
)
np.testing.assert_array_equal(hazard.event_name, [""] * 4)
np.testing.assert_array_equal(
hazard.event_name, ["1999-01-01", "1999-02-01", "2000-01-01", "2000-02-01"]
)

def test_errors(self):
"""Check if expected errors are thrown"""
Expand Down

0 comments on commit c8d5b7f

Please sign in to comment.