Source code for pycif.plugins.datastreams.meteos.chimere_meteo.read

import os
import datetime
import numpy as np
import xarray as xr

from .....utils.netcdf import readnc
from .....utils.check.errclass import CifValueError


[docs] def read( self, name, varnames, dates, files, interpol_flx=False, comp_type=None, ddi=None, **kwargs ): """Read requested variables from CHIMERE METEO.nc files. For each ``[period, file]`` pair, reads ``varnames`` (falling back to ``name`` if ``varnames`` is empty) and the ``Times`` variable from the file, parses ``Times`` to locate the array index matching the requested period start (optionally offset from ``ddi`` instead of the file's own first time stamp), and extracts that hourly slice. Args: self: the meteo Plugin (uses ``self.model.periods`` when raising the interpolation-misconfiguration error). name: name of the component/variable to read, used as a fallback when ``varnames`` is empty. varnames: name of the NetCDF variable to extract; must not be an empty string. dates: list of ``[start, end]`` date pairs, aligned with ``files``. files: list of CHIMERE METEO.nc files to read from, aligned with ``dates``. interpol_flx (bool): unused here (kept for interface consistency). comp_type: unused here (kept for interface consistency). ddi: optional reference date used instead of the file's first ``Times`` entry to compute the hourly index to extract. Returns: xarray.DataArray: extracted data stacked over ``dates``, with dims ``(time, lev, lat, lon)``. Raises: CifValueError: if ``varnames`` is an empty string, which happens when the meteo needs interpolating to another domain or temporal resolution but the input datavect does not list all required variables explicitly. """ # Raise Exception if varname is empty string if varnames == '': raise CifValueError( "Varname is empty string. Can't read raw meteo files.\n" "This happens when trying to spatially or temporally interpolate input files " "to another domain or temporal resolution.\n" "If one want to interpolate a METEO file to another domain, " "ALL meteo variables should be included explicitly in the datavect of the YAML file.\n" "Please also check that the temporal split (e.g., METEO files per 24h period) " "is the same in the input and in the model resolution.\n" f"In the present case, the expected sub-period length is: {self.model.periods} " f"whereas file Time length is {len(readnc(files[0], ['Times'])) - 1}h" ) var2extract = varnames if varnames != "" else name # Reading required meteo files trcr_met = [] for period, ff in zip(dates, files): data, times = readnc(ff, [var2extract, "Times"]) # Force conversion to float64 data = data.astype(float) # Get the correct hour in the file times = [ datetime.datetime.strptime( str(b"".join(s), "utf-8"), "%Y-%m-%d_%H:%M:%S" ) for s in times ] hour = int((period[0] - times[0]).total_seconds() // 3600) if ddi is not None: hour = int((period[0] - ddi).total_seconds() // 3600) trcr_met.append(data[hour, ...]) # Building a xarray xmod = xr.DataArray( trcr_met, coords={"time": np.array(dates)[:, 0]}, dims=("time", "lev", "lat", "lon") ) return xmod