Skip to content

Commit

Permalink
Improve reconstruction of date_start
Browse files Browse the repository at this point in the history
  • Loading branch information
lucduron committed Mar 2, 2024
1 parent aa7fa74 commit 33de263
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
8 changes: 8 additions & 0 deletions tests/io_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ def test_to_netcdf(tmp_path, slf_in):
@TIDAL_FLATS
def test_to_selafin(tmp_path, slf_in):
ds_slf = xr.open_dataset(slf_in, engine="selafin")

# Remove some data which is rebuilt
del ds_slf.attrs["date_start"]

slf_out = tmp_path / "test.slf"
ds_slf.selafin.write(slf_out)
ds_slf2 = xr.open_dataset(slf_out, engine="selafin")
Expand All @@ -75,6 +79,10 @@ def test_to_selafin(tmp_path, slf_in):
@TIDAL_FLATS
def test_to_selafin_eager_mode(tmp_path, slf_in):
ds_slf = xr.open_dataset(slf_in, lazy_loading=False, engine="selafin")

# Remove some data which is rebuilt
del ds_slf.attrs["date_start"]

slf_out = tmp_path / "test.slf"
ds_slf.selafin.write(slf_out)
ds_slf2 = xr.open_dataset(slf_out, engine="selafin")
Expand Down
26 changes: 22 additions & 4 deletions xarray_selafin/xarray_backend.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
from datetime import datetime
from datetime import timedelta
from operator import attrgetter

import numpy as np
import xarray as xr
Expand Down Expand Up @@ -49,12 +50,26 @@ def write_serafin(fout, ds):
except KeyError:
pass # Default: ">"

try:
slf_header.nb_frames = ds.time.size
except AttributeError:
slf_header.nb_frames = 0

try:
slf_header.date = ds.attrs["date_start"]
except KeyError:
raise RuntimeError

slf_header.nb_frames = ds.time.size
# Retrieve starting date from first time
if slf_header.nb_frames == 0:
first_time = ds.time
else:
first_time = ds.time[0]
first_date_str = first_time.values.astype(str) # "1900-01-01T00:00:00.000000000"
first_date_str = first_date_str.rstrip("0") + "0" # "1900-01-01T00:00:00.0"
try:
date = datetime.strptime(first_date_str, '%Y-%m-%dT%H:%M:%S.%f')
slf_header.date = attrgetter("year", "month", "day", "hour", "minute", "second")(date)
except ValueError:
slf_header.date = (1900, 1, 1, 0, 0, 0)

# Variables
for var in ds.data_vars:
Expand Down Expand Up @@ -130,7 +145,10 @@ def write_serafin(fout, ds):

t0 = np.datetime64(datetime(*slf_header.date))

time_serie = compute_duration_between_datetime(t0, ds.time.values)
try:
time_serie = compute_duration_between_datetime(t0, ds.time.values)
except AttributeError:
return # no time (header only is written)
if isinstance(time_serie, float):
time_serie = [time_serie]
for it, t_ in enumerate(time_serie):
Expand Down

0 comments on commit 33de263

Please sign in to comment.