Source code for pycif.plugins.datastreams.fluxes.chimere.read
import datetime
import os
import numpy as np
import xarray as xr
import resource
from .....utils.netcdf import readnc
from .....utils.check.errclass import CifError
from .....utils.hdf5 import _hdf5_lock
[docs]
def read(
self,
name,
varnames,
dates,
files,
interpol_flx=False,
tracer=None,
model=None,
ddi=None,
**kwargs
):
"""Get fluxes from pre-computed CHIMERE AEMISSIONS/BEMISSIONS files.
For each requested date, extracts the matching hourly slice of the
requested variable, the hour index being computed from ``ddi`` (if given)
or from the file's ``Times`` variable. If ``tracer.diurnal_factor`` is
set, the diurnal cycle of the flux is rescaled toward its daily mean
while conserving the daily total (EXPERIMENTAL).
Args:
self: the fluxes Plugin.
name (str): name of the component.
varnames (list[str] or str): variable name(s) to read; ``name`` is
used if ``varnames`` is empty.
dates (list): list of the date intervals to extract.
files (list): list of files matching ``dates``.
interpol_flx (bool): unused, kept for interface compatibility.
tracer: the tracer Plugin, giving access to ``diurnal_factor``.
model: unused, kept for interface compatibility.
ddi (datetime.datetime, optional): reference start date of the file,
used to compute the hour index directly; if ``None``, the hour
is instead derived from the file's ``Times`` variable.
**kwargs: unused, kept for interface compatibility.
Returns:
xr.DataArray: the flux data with dimensions
``(time, lev, lat, lon)``.
Raises:
CifError: if ``ddi`` is not given and the file has no ``Times``
variable to derive the hour index from.
"""
var2extract = varnames if varnames != "" else name
# Each file usually covers many dates: read it only once
dates_per_file = {}
for idate, ff in enumerate(files):
dates_per_file.setdefault(ff, []).append(idate)
trcr_flx = [None] * len(dates)
for ff, idates in dates_per_file.items():
with _hdf5_lock, xr.open_dataset(ff) as ds:
# Force conversion to float64
data = ds[var2extract].values.astype(float)
# Get the start date of the file
if ddi is not None:
file_start = ddi
else:
if "Times" not in ds:
raise CifError("Times variables is not available and I have "
"no information on the file date")
# Times are decoded as strings or as arrays of characters
file_start = ds["Times"].values[0]
if np.ndim(file_start) == 1:
file_start = b"".join(file_start)
if isinstance(file_start, bytes):
file_start = file_start.decode()
file_start = datetime.datetime.strptime(
str(file_start), "%Y-%m-%d_%H:%M:%S")
# Scale the diurnal cycle
if hasattr(tracer, "diurnal_factor"):
data = tracer.diurnal_factor * data \
+ (1 - tracer.diurnal_factor) * data.mean(axis=0)
for idate in idates:
hour = int(
(dates[idate][0] - file_start).total_seconds() // 3600)
trcr_flx[idate] = data[hour, ...]
# Building a xarray
xmod = xr.DataArray(
trcr_flx, coords={"time": np.array(dates)[:, 0]},
dims=("time", "lev", "lat", "lon")
)
return xmod