Source code for pycif.plugins.models.wrfchem.io.inputs.make_latcond

import os
import shutil
import filecmp
from netCDF4 import Dataset
import numpy as np
import xarray as xr
import pandas as pd
import pathlib

from logging import warning

from ......utils import path
from ......utils.check.errclass import CifValueError
# from .utils import replace_dates

# Copied from chimere on 2022-01-03, adapted to wrf


[docs] def make_latcond(self, datastore, runsubdir, datei, mode): """ Generates boundary conditions files for wrf (Could merge with make_inicond, it's pretty much the same) :param self: :param datastore: :type datastore: dict :param runsubdir: :type runsubdir: str :param mode: :return: """ # List of dates for which emissions are needed # freum: all uses commented # list_dates = pd.date_range(ddi, periods=self.nhours + 1, freq="h") # Name of variable in netCDF # freum: all uses commented # nc_varname = "top_conc" if input_type == "topcond" else "lat_conc" # Fixed name for BC files fileout = f"{runsubdir}/wrfbdy_d01" # Loop on all active species # If in datastore, take data, otherwise, link to original BOUN_CONCS for spec in self.chemistry.acspecies.attributes: trid = ("latcond", spec) # If spec not explicitly defined in datastore, # fetch general component information if available if trid in datastore: pass elif trid not in datastore and ("latcond", "") in datastore: trid = ("latcond", "") else: continue tracer = datastore[trid] tracer_data = tracer["data"][datei] # If no data is provided, just copy from original file if "spec" not in tracer_data: dirorig = tracer["dirorig"] fileorig = tracer["fileorig"] fileini = f"{dirorig}/{fileorig}" # If does not exist, just link # linked = False if not os.path.isfile(fileout): path.link(fileini, fileout) # freum: comment again, same as in fluxes and inicond # # Otherwise, check for difference # if not linked: # if not os.path.isfile(fileini): # warning("The boundary condition file {} does not exist to " # "initialize the species {}. The concentrations will" # " be initialized to zero. Please check your yaml if" # " you expect a different behaviour" # .format(fileini, spec)) # continue # # if not filecmp.cmp(fileini, fileout): # with Dataset(fileini, "r") as ds: # ljust_specs_in = ds.variables["species"][:].astype(str) # specs_in = ["".join(p).strip() for p in ljust_specs_in] # # if spec not in specs_in: # warning("{} is not accounted " # "for in the boundary conditions file {}. " # "Please check your LBC whether it should be" # .format(spec, fileini)) # continue # # ispec = specs_in.index(spec) # # if input_type == "latcond": # lbcin = ds.variables["lat_conc"][..., ispec] # lbcin = lbcin[..., np.newaxis, :] # else: # lbcin = ds.variables["top_conc"][..., ispec] # lbcin = lbcin[:, np.newaxis, ...] # # lbcin = xr.DataArray( # lbcin, # coords={"time": list_dates}, # dims=("time", "lev", "lat", "lon"), # ) # # # If lbc file is still a link, should be copied # # to be able to modify it locally # if os.path.islink(fileout): # file_orig = pathlib.Path(fileout).resolve() # os.unlink(fileout) # shutil.copy(file_orig, fileout) # # # Now writes the new value for the corresponding species # self.latcond.write(spec, fileout, lbcin, # comp_type=input_type) else: # Copy wrfinput file(s) from source_dir (assumes that # real.exe already ran) # (Only do this once) if os.path.islink(fileout): raise CifValueError("Link shouldnt exist...?") if not os.path.exists(fileout): shutil.copy(os.path.join(self.source_dir, "wrfbdy_d01"), fileout) # Write boundary conditions lbc_fwd = tracer_data["spec"] varname = getattr(self.chemistry.acspecies, spec).varname self.latcond.write(varname, fileout, lbc_fwd, comp_type="latcond")
# freum: no tl mode for wrf # if mode == "tl": # path.copyfromlink(fileoutincr) # lbc_tl = tracer_data.get("incr", 0.0 * lbc_fwd) # self.latcond.write( # spec, fileoutincr, lbc_tl, comp_type=input_type # ) # Check that the dates are consistent with what CHIMERE expects # freum: check for dates in file commented, because wrf checks that too # replace_dates(fileout, list_dates, self.ignore_input_dates) # freum: no tl mode for wrf # # Repeat operations for tangent linear # # Needed to initialize the TL to zero for other species # if mode != "tl": # continue # # if "spec" not in tracer_data: # # If does not exist, just link # if not os.path.isfile(fileoutincr): # shutil.copy(fileini, fileoutincr) # # with Dataset(fileoutincr, "a") as fout: # nc_var_out = fout.variables[nc_varname][:] # nc_names = [ # str(b"".join(s).strip().lower(), "utf-8") # for s in fout.variables["species"][:] # ] # if spec.lower() not in nc_names: # continue # # # Apply to original data # nc_var_out[..., nc_names.index(spec.lower())][:] = 0.0 # # fout.variables[nc_varname][:] = nc_var_out # # replace_dates(fileoutincr, list_dates, self.ignore_input_dates)