Source code for pycif.plugins.datastreams.fields.lmdz_outfields_nc.read
import numpy as np
import xarray as xr
import os
import datetime
import tracemalloc
from .....utils.hdf5 import _hdf5_lock
[docs]
def read(
self,
name,
varnames,
dates,
files,
interpol_flx=False,
tracer=None,
model=None,
**kwargs
):
"""Read a variable from LMDz ``trajq`` files into a pyCIF DataArray.
Opens each distinct file in ``files`` once, matches each requested
date against the file's ``time`` coordinate (since the file may cover
a different month/year range than strictly requested), and stacks the
selected ``(lev, lat, lon)`` slices into a single array.
Args:
self: The field/tracer Plugin.
name: Name of the component; used as fallback variable name.
varnames: Name of the variable to read; if empty, ``name`` is used
instead.
dates: List of date entries to extract, matching ``files``.
files: List of files matching ``dates``; each distinct file is
opened only once.
interpol_flx: Unused.
tracer: Unused.
model: Unused.
**kwargs: Unused.
Returns:
xarray.DataArray: A 4-dimensional ``(time, lev, lat, lon)`` array.
"""
# Reading required lmdz files
trcr_lmdz = []
trcr_dates = []
data = None
file_ref = ""
for dd, file_concs in zip(dates, files):
if file_concs != file_ref:
file_ref = file_concs
# Reading file
with _hdf5_lock:
with xr.open_dataset(file_concs) as ds:
data = ds[varnames if len(varnames) > 0 else name].load()
# Flip upside down
# TODO: check once for all whether to flip North-South...
# data = data[:, :, ::-1]
# Get correct data index
# as the month/year may be different
# in the file than the one required
times = ds["time"].to_pandas().dt.to_pydatetime()
ind = np.where(times == dd[0])[0][0]
# Appending
trcr_lmdz.append(data[ind, ...].values)
trcr_dates.append(dd[0])
# Putting the data into an xarray
xmod = xr.DataArray(
trcr_lmdz, coords={"time": trcr_dates}, dims=("time", "lev", "lat", "lon")
)
return xmod