ecmwf / cfgrib

A Python interface to map GRIB files to the NetCDF Common Data Model following the CF Convention using ecCodes
Apache License 2.0
409 stars 77 forks source link

Writing of grib files loses time dimension #305

Open clessig opened 2 years ago

clessig commented 2 years ago

I have the following code (slightly simplified for reproducibility):

import numpy as np
import xarray as xr
from cfgrib.xarray_to_grib import to_grib

# 865_128_256_f32.dat
ntime = 865
nlats = 128
nlons = 256
lats = np.linspace( 0, np.pi, nlats)
lons = np.linspace( 0, np.pi, nlons)
times = list(range( ntime))

vorticity = np.random.randn( ntime, nlats, nlons)

ds2 = xr.DataArray( vorticity, coords=[times, lats, lons],
                        dims=['time', 'latitude', 'longitude'],).to_dataset(name='vo')
ds2.vo.attrs['GRIB_shortName'] = 'vo'

fname_out = 'sh_shallow_vorticity.grib'
to_grib( ds2, fname_out)

ds2 looks correct

>>> ds2 = xr.DataArray( vorticity, coords=[times, lats, lons], dims=['time', 'latitude', 'longitude'],).to_dataset(name='vo')
>>> ds2
<xarray.Dataset>
Dimensions:    (latitude: 128, longitude: 256, time: 8641)
Coordinates:
  * time       (time) int64 0 1 2 3 4 5 6 ... 8634 8635 8636 8637 8638 8639 8640
  * latitude   (latitude) float64 0.0 0.02474 0.04947 ... 3.092 3.117 3.142
  * longitude  (longitude) float64 0.0 0.01232 0.02464 ... 3.117 3.129 3.142
Data variables:
    vo         (time, latitude, longitude) float32 4.53e-05 ... -9.787e-07
>>> ds2.vo.attrs['GRIB_shortName'] = 'vo'
>>> ds2
<xarray.Dataset>
Dimensions:    (latitude: 128, longitude: 256, time: 8641)
Coordinates:
  * time       (time) int64 0 1 2 3 4 5 6 ... 8634 8635 8636 8637 8638 8639 8640
  * latitude   (latitude) float64 0.0 0.02474 0.04947 ... 3.092 3.117 3.142
  * longitude  (longitude) float64 0.0 0.01232 0.02464 ... 3.117 3.129 3.142
Data variables:
    vo         (time, latitude, longitude) float32 4.53e-05 ... -9.787e-07

However, when I re-load the file the time dimension is lost:

>>> xr.open_dataset( '../data/rsw/test/sh_shallow_vorticity.grib', engine='cfgrib')
<xarray.Dataset>
Dimensions:     (latitude: 128, longitude: 256)
Coordinates:
    time        datetime64[ns] ...
    step        timedelta64[ns] ...
    surface     float64 ...
  * latitude    (latitude) float64 0.0 0.02474 0.04947 ... 3.092 3.117 3.142
  * longitude   (longitude) float64 0.0 0.01232 0.02464 ... 3.117 3.129 3.142
    valid_time  datetime64[ns] ...
Data variables:
    vo          (latitude, longitude) float32 ...
Attributes:
    GRIB_edition:            2
    GRIB_centre:             consensus
    GRIB_centreDescription:  Consensus
    GRIB_subCentre:          0
    Conventions:             CF-1.7
    institution:             Consensus
    history:                 2022-06-14T10:26 GRIB to CDM+CF via cfgrib-0.9.1...