import datetime
import glob
import os
import numpy as np
import xarray as xr
from logging import info
from .....utils.netcdf import readnc
from .....utils.check.errclass import CifError
[docs]
def read(
self,
name,
tracdir,
tracfile,
varnames,
dates,
interpol_flx=False,
tracer=None,
model=None,
**kwargs
):
"""Read GCP N2O fluxes for the requested dates into a pyCIF array.
``tracfile`` may be given as a single file-name-format string
(broadcast to all dates) or as a list of the same length as ``dates``.
For each date/file pair, reads the requested variable plus ``TIME`` and
``LAT`` via :func:`~pycif.utils.netcdf.readnc`, computes the month index
from the year encoded at the start of the file name, and extracts the
corresponding time slice; latitude order is flipped if the file's
``LAT`` is decreasing.
Args:
self: the fluxes Plugin.
name: the name of the component; unused directly, kept for
interface compatibility.
tracdir: unused directly, kept for interface compatibility.
tracfile (str or list[str]): file name (format) or list of file
names to read from, one per date if a list.
varnames (str): variable name to read from the file.
dates (list[datetime.datetime]): list of dates to extract.
interpol_flx (bool): unused, kept for interface compatibility.
tracer: unused, kept for interface compatibility.
model: unused, kept for interface compatibility.
**kwargs: unused, kept for interface compatibility.
Returns:
xr.DataArray: the flux data with dimensions
``(time, lev, lat, lon)``.
Raises:
CifError: if ``tracfile`` is a list whose length does not match
``dates``.
"""
# tracfile can be a list of same length as dates
if type(tracfile) == str:
tracfile = [tracfile[:]]
if len(tracfile) != len(dates) \
and len(tracfile) > 1:
raise CifError(
f"Try read GCP files from a list of dates and a list of files, but not of same length:\n{tracfile}\n{dates}"
)
elif len(tracfile) == 1:
list_files = len(dates) * tracfile
else:
list_files = tracfile[:]
# Reading fluxes for periods within the simulation window
trcr_flx = []
for dd, dd_file in zip(dates, list_files):
file_flx = dd.strftime(dd_file)
fluxes = readnc(file_flx, [varnames])
#print('FFFFFFFFFFFFFFFFFF',fluxes.shape)
time = readnc(file_flx, ['TIME'])
lat = readnc(file_flx,['LAT'])
year_beg_file = int((dd_file.split('-')[0]).split('.')[-1])
index_dd = (dd.year - year_beg_file) * 12 + dd.month -1
trcr_flx.append(fluxes[index_dd, :, :])
if lat[1] < lat[0]:
xmod = xr.DataArray(
np.array(trcr_flx)[:, np.newaxis, ::-1,:],
coords={"time": dates},
dims=("time", "lev", "lat", "lon"),
)
else:
xmod = xr.DataArray(
np.array(trcr_flx)[:, np.newaxis, :,:],
coords={"time": dates},
dims=("time", "lev", "lat", "lon"),
)
return xmod