Skip to content

Commit 4d5ec56

Browse files
Merge pull request #76 from EcoExtreML/fix_issue_74
Add time units and calendar when writing netcdf
2 parents b35bd24 + 81c6b15 commit 4d5ec56

2 files changed

Lines changed: 16 additions & 3 deletions

File tree

PyStemmusScope/save.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ def to_netcdf(config_file: str, cf_filename: str) -> str:
284284
)
285285

286286
# get time info
287-
time = forcing_dict["time"].values
287+
time = forcing_dict["time"]
288288

289289
# read convention file
290290
conventions = pd.read_csv(cf_filename)
@@ -327,11 +327,18 @@ def to_netcdf(config_file: str, cf_filename: str) -> str:
327327
# update dimensions
328328
dataset = _update_dataset_attrs_dims(dataset, forcing_dict)
329329

330-
# # save to nc file
330+
# for writing to netcdf, time attrs should be added
331+
# time attrs should be the same as plumber 2 forcing data
332+
# otherwise it cannot be uploaded to modelevaluation portal
333+
start_time = time.dt.strftime("%Y-%m-%d").values[0]
334+
time_encode = {
335+
"time": {"units": f"seconds since {start_time}", "calendar": "standard"}
336+
}
337+
# save to nc file
331338
nc_filename = (
332339
Path(config["OutputPath"])
333340
/ f"{Path(config['OutputPath']).stem}_STEMMUS_SCOPE.nc"
334341
)
335-
dataset.to_netcdf(path=nc_filename)
342+
dataset.to_netcdf(path=nc_filename, encoding=time_encode)
336343

337344
return str(nc_filename)

tests/test_save.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,3 +372,9 @@ def test_save_to_netcdf(self, cf_convention, _make_csv_file, model_with_setup):
372372
assert "z" in dataset
373373
# check z attributes
374374
assert "layer_1: 0.0 - 1.0 cm" in dataset["z"].attrs["definition"]
375+
376+
# test time attrs
377+
start_time = forcing_data["time"].dt.strftime("%Y-%m-%d").values[0]
378+
dataset = xr.open_dataset(saved_nc_file, decode_times=False)
379+
assert dataset.time.attrs["units"] == f"seconds since {start_time}"
380+
assert dataset.time.attrs["calendar"] == "standard"

0 commit comments

Comments
 (0)