Skip to content

Commit 48b6d40

Browse files
Merge pull request #1181 from CLIMADA-project/adapt_hdf5_write_from
Adapt Hazard from_hdf5 and write_hdf5 to forecast attributes
2 parents 8a63b43 + 9ce7f73 commit 48b6d40

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

climada/hazard/io.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -917,6 +917,10 @@ def write_hdf5(self, file_name, todense=False):
917917
# Centroids have their own write_hdf5 method,
918918
# which is invoked at the end of this method (s.b.)
919919
continue
920+
elif var_name == "lead_time":
921+
hf_data.create_dataset(
922+
var_name, data=var_val.astype("timedelta64[ns]").astype("int64")
923+
)
920924
elif isinstance(var_val, sparse.csr_matrix):
921925
if todense:
922926
hf_data.create_dataset(var_name, data=var_val.toarray())
@@ -987,7 +991,11 @@ def from_hdf5(cls, file_name):
987991
continue
988992
if var_name == "centroids":
989993
continue
990-
if isinstance(var_val, np.ndarray) and var_val.ndim == 1:
994+
if var_name == "lead_time":
995+
hazard_kwargs[var_name] = np.array(hf_data.get(var_name)).astype(
996+
"timedelta64[ns]"
997+
)
998+
elif isinstance(var_val, np.ndarray) and var_val.ndim == 1:
991999
hazard_kwargs[var_name] = np.array(hf_data.get(var_name))
9921000
elif isinstance(var_val, sparse.csr_matrix):
9931001
hf_csr = hf_data.get(var_name)

climada/hazard/test/test_forecast.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,3 +114,20 @@ def test_hazard_forecast_select(haz_fc, lead_time, member):
114114
npt.assert_array_equal(haz_fc_select.event_id, haz_fc.event_id[np.array([3, 0])])
115115
npt.assert_array_equal(haz_fc_select.member, member[np.array([3, 0])])
116116
npt.assert_array_equal(haz_fc_select.lead_time, lead_time[np.array([3, 0])])
117+
118+
119+
def test_write_read_hazard_forecast(haz_fc, tmp_path):
120+
121+
file_name = tmp_path / "test_hazard_forecast.h5"
122+
123+
haz_fc.write_hdf5(file_name)
124+
haz_fc_read = HazardForecast.from_hdf5(file_name)
125+
126+
assert haz_fc_read.lead_time.dtype.kind == np.dtype("timedelta64").kind
127+
128+
for key in haz_fc.__dict__.keys():
129+
if key in ["intensity", "fraction"]:
130+
(haz_fc.__dict__[key] != haz_fc_read.__dict__[key]).nnz == 0
131+
else:
132+
# npt.assert_array_equal also works for comparing int, float or list
133+
npt.assert_array_equal(haz_fc.__dict__[key], haz_fc_read.__dict__[key])

0 commit comments

Comments
 (0)