Source code for pycif.plugins.datastreams.fluxes.lmdz_bin.read
import numpy as np
import pandas as pd
import xarray as xr
from scipy.io import FortranFile
from logging import info
[docs]
def read(
self,
name,
tracdir,
tracfile,
varnames,
dates,
interpol_flx=False,
**kwargs
):
"""Read LMDZ-DISPERSION fluxes from Fortran unformatted binary files.
For each requested date, opens the corresponding binary file and reads
it record by record until exhaustion; each record holds a pair of
forward and tangent-linear real values per grid cell, reshaped to
``(ndays_in_file, nlat, nlon)`` using the domain's horizontal size.
Timestamps are attributed to each daily record starting at `dd`.
Args:
self: the model Plugin, providing ``domain`` (for ``nlon``/``nlat``).
name: the name of the component
tracdir, tracfile: flux directory and file format (a ``strftime``
pattern applied to each date in `dates`)
varnames: Unused, kept for interface consistency with other flux
plugins.
dates: list of dates to extract
interpol_flx (bool): if True, interpolates fluxes at time t from
values of surrounding available files
Returns:
xr.DataArray: the forward-flux data (from the first requested
file), with dimensions ``(time, lat, lon)``, indexed by the daily
timestamps derived from `dates`.
"""
list_file_flx = [dd.strftime(tracfile) for dd in dates]
trcr_dates = []
trcr_flx = []
trcr_flx_tl = []
for dd, file_flx in zip(dates, list_file_flx):
# Read binary file
data = []
with FortranFile(f"{tracdir}/{file_flx}") as f:
while True:
try:
data.append(f.read_reals())
except BaseException:
info(f"End of file {file_flx}")
break
# Reshape file
nlon = self.domain.nlon
nlat = self.domain.nlat
data = np.array(data)
flx = data[:, 0].reshape((-1, nlat, nlon))
flx_tl = data[:, 1].reshape((-1, nlat, nlon))
trcr_flx.append(flx)
trcr_flx_tl.append(flx_tl)
trcr_dates.extend(list(pd.date_range(dd, freq="D", periods=len(flx))))
xmod = xr.DataArray(
trcr_flx[0], coords={"time": trcr_dates}, dims=("time", "lat", "lon")
)
return xmod