Source code for pycif.plugins.datastreams.fields.gridded_NetCDF_inicond.read

from logging import warning
import xarray as xr

from ....domains.gridded_NetCDF.utils import find_coord
from .....utils.hdf5 import _hdf5_lock


[docs] def read(self, name, varnames, dates, files, interpol_flx=False, comp_type=None, **kwargs): """Read a gridded NetCDF initial-condition field into a pyCIF DataArray. Opens the inicond NetCDF file, renames its latitude/longitude/level coordinates to ``lat``/``lon``/``lev`` (using ``self.vertical_dim_name`` for the vertical coordinate and :func:`~pycif.plugins.domains.gridded_NetCDF.utils.find_coord` for the horizontal ones), optionally sorts latitude/longitude in ascending order, and adds a singleton ``time`` dimension set to the simulation start date. Args: self: The field/tracer Plugin (``vertical_dim_name``, ``sort_lat``, ``sort_lon`` attributes are used). name: Name of the component; used as the variable name if ``varnames`` is not given. varnames: Name of the variable to read in the NetCDF file. dates: List of date entries matching ``files``; only the first date is used as the initial date. files: List of files matching ``dates``; only the first file is read (a warning is issued if more than one is given). interpol_flx: Unused. comp_type: Unused. **kwargs: Unused. Returns: xarray.DataArray: A 4-dimensional ``(time, lev, lat, lon)`` array. """ if len(files) > 1: warning("multiple inicond files to read, " "reading the first one and ignoring all others") inicond_file = files[0] initial_date = dates[0][0] # Getting inicond dataarray varnames = varnames if varnames else name with _hdf5_lock: xmod = xr.open_dataset(inicond_file)[varnames] # Getting coordinates names lev_coord_name = self.vertical_dim_name lat_coord_name = find_coord(xmod, 'latitude', 'lat') lon_coord_name = find_coord(xmod, 'longitude', 'lon') # Renaming spatial coordinates to 'lev', 'lat' and 'lon' xmod = xmod.rename({lat_coord_name: 'lat', lon_coord_name: 'lon', lev_coord_name: 'lev'}) # TODO: need to also rename the dimensions associated with lat, lon and time # if they have a different name than the coordinates. # Sorting latitudes and longitudes in ascending order dims_to_sort = [] if self.sort_lat: dims_to_sort.append('lat') if self.sort_lon: dims_to_sort.append('lon') if dims_to_sort: xmod = xmod.sortby(dims_to_sort) # Adding 'time' dimension and coordinate if 'time' in xmod.dims: xmod = xmod.isel(time=0) xmod = xmod.expand_dims(['time']) xmod['time'] = (['time'], [initial_date]) # Reordering dimensions xmod = xmod.transpose('time', 'lev', 'lat', 'lon') return xmod