Source code for pycif.plugins.datastreams.fields.chimere_icbc.read

import datetime
import os

import numpy as np
import xarray as xr
from netCDF4 import Dataset
from logging import debug

from .....utils.netcdf import readnc


[docs] def read( self, name, varnames, dates, files, interpol_flx=False, comp_type=None, ddi=None, **kwargs ): """Get fluxes from pre-computed fluxes and load them into a pyCIF variables Args: self: the fluxes Plugin name: the name of the component tracdir, tracfile: flux directory and file format dates: list of dates to extract interpol_flx (bool): if True, interpolates fluxes at time t from values of surrounding available files """ var2extract = varnames if varnames != "" else name # Check the type of limit condition to check if comp_type is None: raise Exception( "Trying to read limit conditions for CHIMERE, " "but did not specify the type" ) # Read INI_CONCS if comp_type == "inicond": ic_file = files[0] ds = xr.open_dataset(ic_file) data = ds[var2extract][:] # Differentiate case when inicond or end files if "Time" not in data.dims: data = data.values[np.newaxis, :] else: data = data.values xmod = xr.DataArray( data, coords={"time": [np.min(dates)]}, dims=("time", "lev", "lat", "lon"), ) # Read Lateral boundary conditions elif comp_type in ["latcond", "topcond"]: # Reading required field files trcr_bc = [] out_dates = [] for dd, ff in zip(dates, files): # Getting the data spec = "lat_conc" if comp_type == "latcond" else "top_conc" data, times, specs = readnc(ff, [spec, "Times", "species"]) # Get the correct date and species index try: ispec = [ "".join(c).strip() for c in specs.astype(str) ].index(var2extract) except ValueError: ispec = -1 try: idate = [ datetime.datetime.strptime("".join(d), "%Y-%m-%d_%H:%M:%S") for d in times.astype(str) ].index(dd[0]) except ValueError: debug("Try to read date {} in file {}, but not available. " "Using index from {} to fetch correct date".format( dd[0], ff, ddi )) if ddi is None: raise Exception("Could not find correct index in {} " "because ddi was not given" .format(ff)) idate = int((dd[0] - ddi).total_seconds() // 3600) # Appending if ispec == -1: #### ajouter and fill_with_zeros: + voir si on met vraiment des 0 ou juste rien du tout = selon ce que fait CHIMERE ensuite trcr_bc.append(data[idate, ..., 0] * 0.0) else: trcr_bc.append(data[idate, ..., ispec]) out_dates.append(dd[0]) # Putting the data into an xarray # Adding an empty latitude axis if comp_type == "latcond": xout = np.array(trcr_bc)[..., np.newaxis, :] else: xout = np.array(trcr_bc)[:, np.newaxis, ...] xmod = xr.DataArray( xout, coords={"time": out_dates}, dims=("time", "lev", "lat", "lon") ) else: raise Exception( "Could not recognize the type of boundary condition " "to read in CHIMERE: {}".format(comp_type) ) return xmod