diff --git a/ESMF_Mesh_Domain_Configuration_Production/NextGen_hyfab_to_ESMF_Mesh.py b/ESMF_Mesh_Domain_Configuration_Production/NextGen_hyfab_to_ESMF_Mesh.py index 532995b4..0e3382ab 100644 --- a/ESMF_Mesh_Domain_Configuration_Production/NextGen_hyfab_to_ESMF_Mesh.py +++ b/ESMF_Mesh_Domain_Configuration_Production/NextGen_hyfab_to_ESMF_Mesh.py @@ -1,11 +1,12 @@ +import argparse +import os +import pathlib +import uuid + import geopandas as gpd import netCDF4 import numpy as np import pandas as pd -import argparse -import pathlib -import os -import uuid gpd.options.display_precision = 16 np.set_printoptions(precision=128) @@ -33,7 +34,7 @@ def convert_hyfab_to_esmf(hyfab_gpkg: pathlib.Path, esmf_mesh_output: pathlib.Pa # for orientation properties since there are issues # with geopandas for converting crs and translating # orientation of polygon from original dataset - hyfab_cart = gpd.read_file(hyfab_gpkg, layer='divides') + hyfab_cart = gpd.read_file(hyfab_gpkg, layer="divides") hyfab_cart = hyfab_cart.sort_values(by=["div_id"]) hyfab = hyfab_cart.to_crs("WGS84") @@ -51,23 +52,25 @@ def convert_hyfab_to_esmf(hyfab_gpkg: pathlib.Path, esmf_mesh_output: pathlib.Pa hyfab_coords[:, 1] = false_ids # Sort data by feature id and reset index - hyfab['element_id'] = false_ids - hyfab_cart['element_id'] = false_ids + hyfab["element_id"] = false_ids + hyfab_cart["element_id"] = false_ids # Get element count element_count = len(hyfab.element_id) # find the number of nodes in first element # based on geometry type - if (hyfab.geometry[0].geom_type == "Polygon"): + if hyfab.geometry[0].geom_type == "Polygon": dup_df = pd.DataFrame([]) - dup_df['node_x'], dup_df['node_y'] = hyfab.geometry[0].exterior.coords.xy - dup_df = dup_df.drop_duplicates(subset=['node_x', 'node_y'], keep='first') + dup_df["node_x"], dup_df["node_y"] = hyfab.geometry[0].exterior.coords.xy + dup_df = dup_df.drop_duplicates(subset=["node_x", "node_y"], keep="first") elem_max_nodes = len(dup_df) else: dup_df = pd.DataFrame([]) - dup_df['node_x'], dup_df['node_y'] = hyfab.geometry[0].geoms._get_geom_item(0).exterior.xy - dup_df = dup_df.drop_duplicates(subset=['node_x', 'node_y'], keep='first') + dup_df["node_x"], dup_df["node_y"] = ( + hyfab.geometry[0].geoms._get_geom_item(0).exterior.xy + ) + dup_df = dup_df.drop_duplicates(subset=["node_x", "node_y"], keep="first") elem_max_nodes = len(dup_df) # Allocate element arrays for center point calculations @@ -84,15 +87,17 @@ def convert_hyfab_to_esmf(hyfab_gpkg: pathlib.Path, esmf_mesh_output: pathlib.Pa # based on geometry type total_num_nodes = 0 for i in range(element_count): - if (hyfab.geometry[i].geom_type == "Polygon"): + if hyfab.geometry[i].geom_type == "Polygon": dup_df = pd.DataFrame([]) - dup_df['node_x'], dup_df['node_y'] = hyfab.geometry[i].exterior.coords.xy - dup_df = dup_df.drop_duplicates(subset=['node_x', 'node_y'], keep='first') + dup_df["node_x"], dup_df["node_y"] = hyfab.geometry[i].exterior.coords.xy + dup_df = dup_df.drop_duplicates(subset=["node_x", "node_y"], keep="first") total_num_nodes += len(dup_df) else: dup_df = pd.DataFrame([]) - dup_df['node_x'], dup_df['node_y'] = hyfab.geometry[i].geoms._get_geom_item(0).exterior.xy - dup_df = dup_df.drop_duplicates(subset=['node_x', 'node_y'], keep='first') + dup_df["node_x"], dup_df["node_y"] = ( + hyfab.geometry[i].geoms._get_geom_item(0).exterior.xy + ) + dup_df = dup_df.drop_duplicates(subset=["node_x", "node_y"], keep="first") total_num_nodes += len(dup_df) # assign current node id and allocate node arrays to extract @@ -107,24 +112,26 @@ def convert_hyfab_to_esmf(hyfab_gpkg: pathlib.Path, esmf_mesh_output: pathlib.Pa # flip node coordinates based on orientation of polygons # from the original cartesian coordinate system for i in range(element_count): - if (hyfab.geometry[i].geom_type == "Polygon"): + if hyfab.geometry[i].geom_type == "Polygon": dup_df = pd.DataFrame([]) - dup_df['node_x'], dup_df['node_y'] = hyfab.geometry[i].exterior.coords.xy - dup_df = dup_df.drop_duplicates(subset=['node_x', 'node_y'], keep='first') + dup_df["node_x"], dup_df["node_y"] = hyfab.geometry[i].exterior.coords.xy + dup_df = dup_df.drop_duplicates(subset=["node_x", "node_y"], keep="first") node_x = dup_df.node_x.values node_y = dup_df.node_y.values ccw = hyfab_cart.geometry[i].exterior.is_ccw else: dup_df = pd.DataFrame([]) - dup_df['node_x'], dup_df['node_y'] = hyfab.geometry[i].geoms._get_geom_item(0).exterior.xy - dup_df = dup_df.drop_duplicates(subset=['node_x', 'node_y'], keep='first') + dup_df["node_x"], dup_df["node_y"] = ( + hyfab.geometry[i].geoms._get_geom_item(0).exterior.xy + ) + dup_df = dup_df.drop_duplicates(subset=["node_x", "node_y"], keep="first") node_x = dup_df.node_x.values node_y = dup_df.node_y.values ccw = hyfab_cart.geometry[i].geoms._get_geom_item(0).exterior.is_ccw num_nodes = len(node_x) element_num_nodes[i] = num_nodes - if (num_nodes > elem_max_nodes): + if num_nodes > elem_max_nodes: elem_max_nodes = num_nodes element_x_coord[i] = hyfab.geometry[i].centroid.coords.xy[0][0] @@ -132,24 +139,34 @@ def convert_hyfab_to_esmf(hyfab_gpkg: pathlib.Path, esmf_mesh_output: pathlib.Pa element_elevation[i] = hyfab.elevation_mean[i] element_slope[i] = hyfab.slope1km_mean[i] - element_slope_azmuith[i] = hyfab.aspect_circmean[i] # NHF aspect is currently in radians, may need to be converted to degrees - - if (ccw): - node_x_coord[node_start:node_start + num_nodes] = np.array(node_x, dtype=np.double) - node_y_coord[node_start:node_start + num_nodes] = np.array(node_y, dtype=np.double) + element_slope_azmuith[i] = hyfab.aspect_circmean[ + i + ] # NHF aspect is currently in radians, may need to be converted to degrees + + if ccw: + node_x_coord[node_start : node_start + num_nodes] = np.array( + node_x, dtype=np.double + ) + node_y_coord[node_start : node_start + num_nodes] = np.array( + node_y, dtype=np.double + ) else: - node_x_coord[node_start:node_start + num_nodes] = np.array(np.concatenate([[node_x[0]], np.flip(node_x[1:])]), dtype=np.double) - node_y_coord[node_start:node_start + num_nodes] = np.array(np.concatenate([[node_y[0]], np.flip(node_y[1:])]), dtype=np.double) + node_x_coord[node_start : node_start + num_nodes] = np.array( + np.concatenate([[node_x[0]], np.flip(node_x[1:])]), dtype=np.double + ) + node_y_coord[node_start : node_start + num_nodes] = np.array( + np.concatenate([[node_y[0]], np.flip(node_y[1:])]), dtype=np.double + ) node_start += num_nodes # Assign node data to pandas dataframe # and calculate the duplicate nodes throughout # the hydrofabric geometry network node_connectivity = pd.DataFrame([]) - node_connectivity['node_x'] = node_x_coord - node_connectivity['node_y'] = node_y_coord + node_connectivity["node_x"] = node_x_coord + node_connectivity["node_y"] = node_y_coord - duplicates = node_connectivity[node_connectivity.duplicated(keep='first')] + duplicates = node_connectivity[node_connectivity.duplicated(keep="first")] # Create array to assign duplicate nodes as # zeroes, while creating unique ids for only @@ -158,25 +175,27 @@ def convert_hyfab_to_esmf(hyfab_gpkg: pathlib.Path, esmf_mesh_output: pathlib.Pa node_id_connectivity = np.empty(len(node_id), dtype=np.int32) node_count = 1 for i in range(len(node_id)): - if (i in duplicates_index): + if i in duplicates_index: node_id_connectivity[i] = 0 else: node_id_connectivity[i] = node_count node_count += 1 # Assign new node id network to dataframe - node_connectivity['node_id'] = node_id_connectivity + node_connectivity["node_id"] = node_id_connectivity # calculate the node id network to include its duplicate ids # for each instance of the node coordinates - ESMF_node_id_connectivity = node_connectivity.groupby(['node_x', 'node_y']).node_id.transform('max') + ESMF_node_id_connectivity = node_connectivity.groupby( + ["node_x", "node_y"] + ).node_id.transform("max") - node_connectivity['node_id_connectivity'] = ESMF_node_id_connectivity.values + node_connectivity["node_id_connectivity"] = ESMF_node_id_connectivity.values node_connectivity_final = node_connectivity.node_id_connectivity.values # Extract only the unique node id network and respective coordinates - node_connectivity = node_connectivity.drop_duplicates('node_id_connectivity') + node_connectivity = node_connectivity.drop_duplicates("node_id_connectivity") node_count = len(node_connectivity) node_x_coord_final = node_connectivity.node_x.values node_y_coord_final = node_connectivity.node_y.values @@ -189,7 +208,9 @@ def convert_hyfab_to_esmf(hyfab_gpkg: pathlib.Path, esmf_mesh_output: pathlib.Pa end_index = 0 for i in range(element_count): end_index += element_num_nodes[i] - elementConn[i, 0:element_num_nodes[i]] = node_connectivity_final[start_index:end_index] + elementConn[i, 0 : element_num_nodes[i]] = node_connectivity_final[ + start_index:end_index + ] start_index = end_index out_dir = os.path.dirname(esmf_mesh_output) @@ -203,9 +224,11 @@ def convert_hyfab_to_esmf(hyfab_gpkg: pathlib.Path, esmf_mesh_output: pathlib.Pa nc = netCDF4.Dataset(temp_path, "w", format="NETCDF4") node_count_dim = nc.createDimension("nodeCount", node_count) elem_count_dim = nc.createDimension("elementCount", element_count) - elem_conn_count_dim = nc.createDimension("connectionCount", len(node_connectivity_final)) + elem_conn_count_dim = nc.createDimension( + "connectionCount", len(node_connectivity_final) + ) node_count_dim = nc.createDimension("coordDim", 2) - node_coords_var = nc.createVariable("nodeCoords", 'f8', ("nodeCount", "coordDim")) + node_coords_var = nc.createVariable("nodeCoords", "f8", ("nodeCount", "coordDim")) node_coords_var.units = "degrees" elem_id = nc.createVariable("element_id", "i4", "elementCount") elem_id.long_name = "False 32-bit catchment IDs use for ESMF mesh generation" @@ -213,7 +236,9 @@ def convert_hyfab_to_esmf(hyfab_gpkg: pathlib.Path, esmf_mesh_output: pathlib.Pa elem_conn_var.long_name = "Node Indices that define the element connectivity" num_elem_conn_var = nc.createVariable("numElementConn", "i", "elementCount") num_elem_conn_var.long_name = "Number of nodes per element" - center_coords_var = nc.createVariable("centerCoords", 'f8', ("elementCount", "coordDim")) + center_coords_var = nc.createVariable( + "centerCoords", "f8", ("elementCount", "coordDim") + ) center_coords_var.units = "degrees" nc.gridType = "unstructured" nc.version = "0.9" @@ -224,7 +249,9 @@ def convert_hyfab_to_esmf(hyfab_gpkg: pathlib.Path, esmf_mesh_output: pathlib.Pa slope_elem_var = nc.createVariable("Element_Slope", "f8", ("elementCount")) slope_elem_var.long_name = "Catchment slope" slope_elem_var.units = "meters" - slope_azi_elem_var = nc.createVariable("Element_Slope_Azmuith", "f8", ("elementCount")) + slope_azi_elem_var = nc.createVariable( + "Element_Slope_Azmuith", "f8", ("elementCount") + ) slope_azi_elem_var.long_name = "Catchment slope azmuith angle" slope_azi_elem_var.units = "Degrees" hgt_elem_var[:] = element_elevation @@ -258,8 +285,14 @@ def convert_hyfab_to_esmf(hyfab_gpkg: pathlib.Path, esmf_mesh_output: pathlib.Pa def get_options(): parser = argparse.ArgumentParser() - parser.add_argument('hyfab_gpkg', type=pathlib.Path, help="Hydrofabric geopackage file pathway") - parser.add_argument("esmf_mesh_output", type=pathlib.Path, help="File pathway to save ESMF netcdf mesh file for hydrofabric") + parser.add_argument( + "hyfab_gpkg", type=pathlib.Path, help="Hydrofabric geopackage file pathway" + ) + parser.add_argument( + "esmf_mesh_output", + type=pathlib.Path, + help="File pathway to save ESMF netcdf mesh file for hydrofabric", + ) return parser.parse_args() diff --git a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/bmi_model.py b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/bmi_model.py index 3c27eacb..35ae7fc2 100755 --- a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/bmi_model.py +++ b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/bmi_model.py @@ -2,14 +2,16 @@ # This is needed for get_var_bytes import gc import hashlib +import logging import os # time debugging import time from collections import defaultdict -from pathlib import Path from datetime import datetime, timezone -import logging +from functools import cached_property +from pathlib import Path + import netCDF4 as nc # import data_tools @@ -34,6 +36,7 @@ ) from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.consts import BMI_MODEL from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.geoMod import ( + GeoMeta, GriddedGeoMeta, HydrofabricGeoMeta, UnstructuredGeoMeta, @@ -68,15 +71,14 @@ try: from ewts.helper import getenv_any from ewts.logger import configure_existing_logger + FORCING_USE_EWTS = True except ImportError: FORCING_USE_EWTS = False -class StdoutStyleFormatter(logging.Formatter): - INFO_FORMAT = ( - "%(asctime)s %(name)-8s %(levelname)-7s %(message)s" - ) +class StdoutStyleFormatter(logging.Formatter): + INFO_FORMAT = "%(asctime)s %(name)-8s %(levelname)-7s %(message)s" DETAILED_FORMAT = ( "%(asctime)s %(name)-8s %(levelname)-7s " @@ -91,7 +93,7 @@ def format(self, record): self._style._fmt = self.DETAILED_FORMAT return super().format(record) - + def formatTime(self, record, datefmt=None): dt = datetime.fromtimestamp(record.created, tz=timezone.utc) return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" @@ -108,6 +110,7 @@ def _configure_stdout_logging(): LOG.propagate = False + # If less than 0, then ESMF.__version__ is greater than 8.7.0 if ESMF.version_compare("8.7.0", ESMF.__version__) < 0: manager = ESMF.api.esmpymanager.Manager(endFlag=ESMF.constants.EndAction.KEEP_MPI) @@ -128,193 +131,167 @@ class NWMv3_Forcing_Engine_BMI_model_Base(Bmi): It includes methods for initializing the model, updating it, accessing model variables, and managing model configuration. This class is responsible for interacting with geospatial data and forcing inputs for the model simulation. - - Attributes - ---------- - _values : dict - Dictionary storing model values. - _start_time : float - The start time for the simulation. - _end_time : float - The end time for the simulation. - _model : object - The model object. - _comm : object - The MPI communicator. - var_array_lengths : int - Length of the variable arrays. - """ - def __init__(self): + def __init__( + self, + b_date: str = None, + geogrid: str = None, + output_path: str = None, + ) -> None: """Create a model that is ready for initialization. Initializes the model with default values for time, variables, and grid types. """ - # This is required prior to the first log message. - if FORCING_USE_EWTS: - val = getenv_any("EWTS_USE_NGEN_BRIDGE", "").strip().lower() - if val in {"1", "true", "yes", "on"}: - configure_existing_logger(LOG) - else: - _configure_stdout_logging() - LOG.warning("ewts package installed but EWTS_USE_NGEN_BRIDGE not on. Falling back to default logging.") - else: - _configure_stdout_logging() + self.output_path = output_path + self._geogrid = geogrid + self._b_date = b_date - super(NWMv3_Forcing_Engine_BMI_model_Base, self).__init__() self._values = {} self._start_time = 0.0 self._end_time = np.finfo(float).max - self._model = None - self._comm = None self.var_array_lengths = 1 # Track output configuration status self._output_configured = False # Initialize attributes in __init__ to avoid PyCharm errors - self.cfg_bmi = None - self._job_meta = None - self._mpi_meta = None - self.geo_meta = None - self._grid_type = None - self._grids = None - self._grid_map = None - self._output_var_names = None - self._var_name_units_map = None - self._var_name_map_long_first = None - self._var_name_map_short_first = None - self._var_units_map = None - self._input_forcing_mod = None - self._supp_pcp_mod = None self._model_parameters_list = [] - - # Diagnostic timing setup - self._call_counts = defaultdict(int) self._call_times = defaultdict(float) - self._total_start = None - - # ---------------------------------------------- - # Required, static attributes of the model - # ---------------------------------------------- - _att_map = BMI_MODEL["att_map"] - - # --------------------------------------------- - # Input variable names (CSDMS standard names) - # --------------------------------------------- - # Forcings engine requires no inputs currently - # and only provides model output - _input_var_names = [] - - _input_var_types = {} - - # ------------------------------------------------------ - # A list of static attributes/parameters. - # ------------------------------------------------------ - _model_parameters_list = [] - - # ------------------------------------------------------------ - # ------------------------------------------------------------ - # BMI: Model Control Functions - # ------------------------------------------------------------ - # ------------------------------------------------------------ - - # ------------------------------------------------------------------- - def initialize(self, config_file: str, output_path: str | None = None) -> None: - """Initialize the model using a configuration file. - - This function is part of the BMI (Basic Model Interface) specification and is automatically - invoked by the BMI system. When running standalone, call `initialize_with_params()` instead, - which sets additional parameters such as `b_date`, `geogrid`, and `output_path`. - - This function is responsible for: - - Setting up core model attributes, grids, and MPI communication. - - Reading the BMI configuration file and initializing basic model components. + self._att_map = BMI_MODEL["att_map"] + self._input_var_names = [] + self._model_parameters_list = [] - :param config_file: The path to the configuration file for model initialization. - :raises RuntimeError: If the configuration file is invalid or missing. - """ + super(NWMv3_Forcing_Engine_BMI_model_Base, self).__init__() - LOG.info("---------------------------") + def init_log(self) -> None: + """Initialize the logging system for the model.""" + # This is required prior to the first log message. + if FORCING_USE_EWTS: + val = getenv_any("EWTS_USE_NGEN_BRIDGE", "").strip().lower() + if val in {"1", "true", "yes", "on"}: + configure_existing_logger(LOG) + else: + _configure_stdout_logging() + LOG.warning( + "ewts package installed but EWTS_USE_NGEN_BRIDGE not on. Falling back to default logging." + ) + else: + _configure_stdout_logging() + LOG.info("-" * 30) LOG.info( - f"BMI Forcing Engine initializing with {config_file}{Pld(St.INITTING, modnm=MODNM)}" + f"BMI Forcing Engine initialized with {self._config_file}{Pld(St.INITTING, modnm=MODNM)}" ) - # -------------- Read in the BMI configuration -------------------------# - if not isinstance(config_file, str) or len(config_file) == 0: + @cached_property + def bmi_cfg_file(self) -> Path: + """Validate and return the BMI configuration file path.""" + if not isinstance(self._config_file, str) or len(self._config_file) == 0: LOG.critical("No BMI initialize configuration provided, nothing to do...") raise RuntimeError( "No BMI initialize configuration provided, nothing to do..." ) - - bmi_cfg_file = Path(config_file).resolve() + bmi_cfg_file = Path(self._config_file).resolve() if not bmi_cfg_file.is_file(): LOG.critical(f"Config file {bmi_cfg_file} not found, nothing to do...") raise RuntimeError( f"Config file {bmi_cfg_file} not found, nothing to do..." ) - - LOG.info(f"Reading config file: {bmi_cfg_file}") - with bmi_cfg_file.open("r") as fp: + return bmi_cfg_file + + @property + def cfg_bmi(self) -> dict: + """Read and parse the BMI configuration file.""" + if self._cfg_bmi is not None: + return self._cfg_bmi + LOG.info(f"Reading config file: {self.bmi_cfg_file}") + with self.bmi_cfg_file.open("r") as fp: cfg = yaml.safe_load(fp) - - self.cfg_bmi = parse_config(cfg) - - # If _job_meta was not set by initialize_with_params(), create a default one - if self._job_meta is None: - self._job_meta = ConfigOptions(self.cfg_bmi) - - # Parse the configuration options - try: - self._job_meta.validate_config(self.cfg_bmi) - except KeyboardInterrupt as e: - err_handler.err_out_screen("User keyboard interrupt", e) - except ImportError as e: - err_handler.err_out_screen("Missing Python packages", e) - except InterruptedError as e: - err_handler.err_out_screen("External kill signal detected", e) - except Exception as e: - err_handler.err_out_screen("Unhandled exception", e) - - # Set NWM version and config, if provided in the config - if self.cfg_bmi.get("NWM_VERSION") is not None: - self._job_meta.nwmVersion = self.cfg_bmi["NWM_VERSION"] - - # Place NWM configuration (if provided by the user). This will be placed into the final - # output files as a global attribute. - if self.cfg_bmi.get("NWM_CONFIG") is not None: - self._job_meta.nwmConfig = self.cfg_bmi["NWM_CONFIG"] - - # Initialize MPI communication - self._mpi_meta = MpiConfig(self._job_meta) - - self.geo_meta = HydrofabricGeoMeta(self._job_meta, self._mpi_meta) - + self._cfg_bmi = parse_config(cfg) + return self._cfg_bmi + + @cfg_bmi.setter + def cfg_bmi(self, value: dict) -> None: + """Set the BMI configuration.""" + self._cfg_bmi = value + + @property + def _job_meta(self) -> ConfigOptions: + """Return the job metadata object.""" + return self.__job_meta + + @_job_meta.setter + def _job_meta(self, value: ConfigOptions) -> None: + """Set the job metadata object.""" + if value is None: + value = ConfigOptions( + self.cfg_bmi, b_date=self._b_date, geogrid=self._geogrid + ) + value.nwmVersion = self.cfg_bmi.get("NWM_VERSION") + value.nwmConfig = self.cfg_bmi.get("NWM_CONFIG") + self.__job_meta = value + + @property + def _mpi_meta(self) -> MpiConfig: + """Return the MPI metadata object.""" + if self.__mpi_meta is None: + self.__mpi_meta = MpiConfig(self._job_meta) + return self.__mpi_meta + + @_mpi_meta.setter + def _mpi_meta(self, value: MpiConfig) -> None: + """Set the MPI metadata object.""" + self.__mpi_meta = value + + @property + def geo_meta(self) -> GeoMeta: + """Return the geospatial metadata object.""" + if self._geo_meta is None: + self._geo_meta = HydrofabricGeoMeta(self._job_meta, self._mpi_meta) + return self._geo_meta + + @geo_meta.setter + def geo_meta(self, value: GeoMeta) -> None: + """Set the geospatial metadata object.""" + self._geo_meta = value + + def init_mpi(self) -> None: + """Set up MPI communication for the model.""" try: comm = MPI.Comm.f2py(self._comm) if self._comm is not None else None self._mpi_meta.initialize_comm(comm=comm) except Exception as e: err_handler.err_out_screen(self._job_meta.errMsg, e) - ### Reassign the scratch dir to a new child dir of the current scratch dir, - ### applying uniqueness to the final path. This must be called by all ranks, once. + def init_scratch_dir(self) -> None: + """Set up the scratch directory for the model, ensuring it is unique for each job. + + Reassign the scratch dir to a new child dir of the current scratch dir, + applying uniqueness to the final path. This must be called by all ranks, once. + """ self._job_meta.uniquefy_scratch_dir_as_child(self._mpi_meta.uid64) - # LOG.debug(f"self._job_meta type: {type(self._job_meta)}") - # Call ESMF mesh creation process + def create_esmf_mesh(self) -> None: + """Create the ESMF mesh for the model.""" if self._mpi_meta.rank == 0: cat_ids = esmf_creation.create_mesh(self._job_meta) - cat_count = np.array([ - len(cat_ids) if self._mpi_meta.rank == 0 else 0 - ], dtype=np.intc) + cat_count = np.array( + [len(cat_ids) if self._mpi_meta.rank == 0 else 0], dtype=np.intc + ) self._mpi_meta.comm.Bcast(cat_count, root=0) if self._mpi_meta.rank != 0: cat_ids = np.empty(cat_count[0], dtype=np.int64) self._mpi_meta.comm.Bcast(cat_ids, root=0) + return cat_ids - # Call forcing_extraction process + def fetch_raw_forcing_data(self) -> None: + """Fetch raw forcing data for the model. + + This function is responsible for retrieving the raw forcing data needed for the model simulation. + It is called during the initialization process and ensures that all necessary data is available + before the model runs. + """ if self._job_meta.nwmConfig not in ["AORC", "NWM"]: if self._mpi_meta.rank == 0: err_handler.log_msg( @@ -332,54 +309,76 @@ def initialize(self, config_file: str, output_path: str | None = None) -> None: ) self._mpi_meta.comm.Barrier() - # Assign grid type to BMI class for grid information - self._grid_type = self._job_meta.grid_type.lower() - self.set_var_names() + @property + def _grid_type(self) -> str: + """Return the grid type of the model.""" + return self._job_meta.grid_type.lower() - # ----- Create some lookup tabels from the long variable names --------# - self._var_name_map_long_first = { + @property + def _var_name_map_long_first(self) -> dict: + """Return the variable name mapping from long names to short names.""" + return { long_name: self._var_name_units_map[long_name][0] for long_name in self._var_name_units_map.keys() } - self._var_name_map_short_first = { + + @property + def _var_name_map_short_first(self) -> dict: + """Return the variable name mapping from short names to long names.""" + return { self._var_name_units_map[long_name][0]: long_name for long_name in self._var_name_units_map.keys() } - self._var_units_map = { + + @property + def _var_units_map(self) -> dict: + """Return the variable units mapping.""" + return { long_name: self._var_name_units_map[long_name][1] for long_name in self._var_name_units_map.keys() } - # Check to make sure we have enough dimensionality to run regridding. We assume that hydrofabric discretizations are large - # enough that 1x1 (single catchment) will provide enough points. For gridded and unstructured domains, we need to make sure - # that the local grid size for each processor is at least 2x2 to run the regridding process. - # forcing_input dimensionality is checked in regrid.py. + @property + def dimensionality(self) -> int: + """Return the dimensionality of the model grid based on the grid type. - dimensionality = 1 if self._grid_type == "hydrofabric" else 2 + Check to make sure we have enough dimensionality to run regridding. We assume that hydrofabric discretizations are large + enough that 1x1 (single catchment) will provide enough points. For gridded and unstructured domains, we need to make sure + that the local grid size for each processor is at least 2x2 to run the regridding process. + forcing_input dimensionality is checked in regrid.py. + """ + return {"hydrofabric": 1}.get(self._grid_type, 2) + def check_dimensionality(self) -> None: + """Check that the local grid size is sufficient for the specified number of cores.""" if ( - self.geo_meta.nx_local < dimensionality - or self.geo_meta.ny_local < dimensionality + self.geo_meta.nx_local < self.dimensionality + or self.geo_meta.ny_local < self.dimensionality ): self._job_meta.errMsg = ( f"You have specified too many cores for your WRF-Hydro grid. " - f"Local grid Must have x/y dimension size of {dimensionality}." + f"Local grid Must have x/y dimension size of {self.dimensionality}." ) err_handler.err_out_screen_para(self._job_meta.errMsg, self._mpi_meta) err_handler.check_program_status(self._job_meta, self._mpi_meta) - # Initialize our output object, which includes local slabs from the output grid. + def init_output_obj(self) -> None: + """Initialize our output object, which includes local slabs from the output grid.""" try: self._output_obj = ioMod.OutputObj(self._job_meta, self.geo_meta) except Exception as e: err_handler.err_out_screen_para(self._job_meta, self._mpi_meta) err_handler.check_program_status(self._job_meta, self._mpi_meta) - # Next, initialize our input forcing classes. These objects will contain - # information about our source products (I.E. data type, grid sizes, etc). - # Information will be mapped via the options specified by the user. - # In addition, input ESMF grid objects will be created to hold data for - # downscaling and regridding purposes. + def init_input_forcing_mod(self) -> None: + """Initialize the input forcing module. + + Next, initialize our input forcing classes. These objects will contain + information about our source products (I.E. data type, grid sizes, etc). + Information will be mapped via the options specified by the user. + In addition, input ESMF grid objects will be created to hold data for + downscaling and regridding purposes. + """ try: self._input_forcing_mod = forcingInputMod.init_dict( self._job_meta, self.geo_meta, self._mpi_meta @@ -388,75 +387,69 @@ def initialize(self, config_file: str, output_path: str | None = None) -> None: err_handler.err_out_screen_para(self._job_meta, self._mpi_meta) err_handler.check_program_status(self._job_meta, self._mpi_meta) - # If we have specified supplemental precipitation products, initialize - # the supp class. + def init_supp_pcp_mod(self) -> None: + """Initialize the supplemental precipitation module, if applicable.""" if self._job_meta.number_supp_pcp > 0: self._supp_pcp_mod = suppPrecipMod.initDict(self._job_meta, self.geo_meta) else: self._supp_pcp_mod = None err_handler.check_program_status(self._job_meta, self._mpi_meta) - # ------------- Initialize the parameters, inputs and outputs ----------# + def initialize_parameters(self) -> None: + """Initialize the parameters, inputs and outputs.""" for parm in self._model_parameters_list: self._values[self._var_name_map_short_first[parm]] = self.cfg_bmi[parm] - self.get_size_of_arrays() - - # for model_input in self.get_input_var_names(): - # self._values[model_input] = np.zeros(self._varsize, dtype=float) - - # Set initial time, step, and true catchment IDs + def set_initial_time_and_step(self, cat_ids) -> None: + """Set the initial time, time step, and cat_ids for the model.""" self._values["current_model_time"] = self.cfg_bmi["initial_time"] self._values["time_step_size"] = self.cfg_bmi["time_step_seconds"] self._values["CAT-ID"] = cat_ids - # Initialize the Forcings Engine model - self._model = NWMv3ForcingEngineModel() + def set_catchment_ids(self) -> None: + """Set catchment ids if using hydrofabric.""" + if self._grid_type == "hydrofabric": + self._values["CAT-ID"] = self.geo_meta.element_ids_global - self._configure_output_path(output_path) + def initialize(self, config_file: str) -> None: + """Initialize the model using a configuration file. - LOG.info(f"BMI Forcing Engine initialized{Pld(St.INITTED, modnm=MODNM)}") + This function is part of the BMI (Basic Model Interface) specification and is automatically + invoked by the BMI system. When running standalone, call `initialize_with_params()` instead, + which sets additional parameters such as `b_date`, `geogrid`, and `output_path`. - def initialize_with_params( - self, - config_file: str, - b_date: str = None, - geogrid: str = None, - output_path: str = None, - ) -> None: - """Initialize the NWMv3 Forcings Engine model with additional job metadata parameters. - - This function **must be called by the user** to fully initialize the NWMv3 Forcings Engine model, - including both core model setup and additional job metadata configuration (such as b_date, geogrid, and output path). - - It performs the following: - - Sets up job metadata (b_date, geogrid) by calling `config_options`. - - Calls the `initialize()` function to handle core model setup (reading the config file, - initializing basic model attributes like MPI, grids, etc.). - - Handles additional configuration options, such as determining the output path - for model results. - - **DO NOT call `initialize()` directly**. Always use this function, which ensures proper - initialization of all necessary parameters and job metadata. - - :param config_file: The configuration file path for the model initialization. - :param b_date: The start date for the simulation. Typically the forecast cycle start time. - :param geogrid: The path to the geospatial grid data, such as a geospatial file for the grid. - :param output_path: The output path for model results. If omitted, a default path will be generated. - :raises ValueError: If an invalid grid type is specified, an exception is raised. + This function is responsible for: + - Setting up core model attributes, grids, and MPI communication. + - Reading the BMI configuration file and initializing basic model components. + + :param config_file: The path to the configuration file for model initialization. + :raises RuntimeError: If the configuration file is invalid or missing. """ - # Set the job metadata parameters (b_date, geogrid) using config_options - self._job_meta = ConfigOptions(self.cfg_bmi, b_date=b_date, geogrid_arg=geogrid) + self._config_file = config_file + for attr in BMI_MODEL[self.__class__.__base__.__name__]: + setattr(self, attr, None) + self._model = NWMv3ForcingEngineModel(self) + self.init_log() + self.init_mpi() + self.init_scratch_dir() + cat_ids = self.create_esmf_mesh() + self.fetch_raw_forcing_data() + self.set_var_names() + self.check_dimensionality() + self.init_output_obj() + self.init_input_forcing_mod() + self.init_supp_pcp_mod() + self.initialize_parameters() + self.get_size_of_arrays() + self.set_initial_time_and_step(cat_ids) + self.set_catchment_ids() - # Now that _job_meta is set, call initialize() to set up the core model - self.initialize(config_file, output_path=output_path) + self._configure_output_path() - def _configure_output_path(self, output_path: str | None = None) -> None: + def _configure_output_path(self) -> None: """Set the output path and initializes the output NetCDF file if forcing output is enabled. This is safe to call once after model initialization. - - :param output_path: Optional override path. """ gpkg_key = self._job_meta.geopackage time_key = str(time.time()).replace(".", "") @@ -472,14 +465,10 @@ def _configure_output_path(self, output_path: str | None = None) -> None: if ext is None: raise ValueError(f"Invalid grid_type: {self._job_meta.grid_type}") - if output_path: - self._output_obj.outPath = output_path + if self.output_path: + self._output_obj.outPath = self.output_path else: - filename = ( - f"NextGen_Forcings_Engine_{ext}_{gpkg_hash}_{time_hash}_output_" - + pd.Timestamp(self._job_meta.b_date_proc).strftime("%Y%m%d%H%M") - + ".nc" - ) + filename = f"NextGen_Forcings_Engine_{ext}_{gpkg_hash}_{time_hash}_output_{pd.Timestamp(self._job_meta.b_date_proc).strftime('%Y%m%d%H%M')}.nc" self._output_obj.outPath = os.path.join( self._job_meta.scratch_dir, filename ) @@ -489,8 +478,7 @@ def _configure_output_path(self, output_path: str | None = None) -> None: ) self._output_configured = True - # ------------------------------------------------------------ - def update(self): + def update(self) -> None: """Update the model by advancing one time step. This method increments the current model time by the time step size @@ -499,13 +487,11 @@ def update(self): :return: None """ - # Run the model to the next timestep self.update_until( self._values["current_model_time"] + self._values["time_step_size"] ) - # ------------------------------------------------------------ - def update_until(self, future_time: float): + def update_until(self, future_time: float) -> None: """Update the model to a specified future time. This method updates the model by running time steps until the @@ -517,24 +503,12 @@ def update_until(self, future_time: float): :return: None """ - # Method for running the model on the initial time if the model has not been run, - # and the future time is the same as the initial time. - if ( self._values["current_model_time"] == future_time == self.cfg_bmi["initial_time"] ): - self._model.run( - self._values, - future_time, - self._job_meta, - self.geo_meta, - self._input_forcing_mod, - self._supp_pcp_mod, - self._mpi_meta, - self._output_obj, - ) + self._model.run(future_time) else: # Start a while loop to iterate the model time step by step until the # current model time reaches or exceeds the future_time. @@ -542,16 +516,7 @@ def update_until(self, future_time: float): # Advance the model time by the defined time step size. self._values["current_model_time"] += self._values["time_step_size"] # Run the model for the new current time and update the state. - self._model.run( - self._values, - self._values["current_model_time"], - self._job_meta, - self.geo_meta, - self._input_forcing_mod, - self._supp_pcp_mod, - self._mpi_meta, - self._output_obj, - ) + self._model.run(self._values["current_model_time"]) # ------------------------------------------------------------ def finalize(self): @@ -570,10 +535,8 @@ def finalize(self): ) # Force destruction of ESMF objects - self.geo_meta = None - self._input_forcing_mod = None - self._supp_pcp_mod = None - self._model = None + for attr in ["geo_meta", "_input_forcing_mod", "_supp_pcp_mod", "_model"]: + setattr(self, attr, None) # Try moving this after all of the ESMF and model bits have # been disposed of - maybe they were keeping something open. @@ -585,13 +548,7 @@ def finalize(self): gc.collect() # make sure objects are deleted from memory LOG.info(Pld(St.COMPLETE, msg="Finishing BMI finalize()", modnm=MODNM)) - # ------------------------------------------------------------------- - # ------------------------------------------------------------------- - # BMI: Model Information Functions - # ------------------------------------------------------------------- - # ------------------------------------------------------------------- - - def get_attribute(self, att_name): + def get_attribute(self, att_name: str) -> Any: """Retrieve an attribute from the model's attribute map. This method searches the `_att_map` dictionary for the specified attribute name @@ -605,11 +562,7 @@ def get_attribute(self, att_name): except Exception as e: LOG.error(f"Could not find attribute: {att_name} - {e}") - # -------------------------------------------------------- - # Note: These are currently variables needed from other - # components vs. those read from files or GUI. - # -------------------------------------------------------- - def get_input_var_names(self): + def get_input_var_names(self) -> list[str]: """Get the list of input variable names. This method returns the list of input variable names defined in the model. @@ -618,7 +571,7 @@ def get_input_var_names(self): """ return self._input_var_names - def get_output_var_names(self): + def get_output_var_names(self) -> list[str]: """Get the list of output variable names. This method returns the list of output variable names defined in the model. @@ -627,8 +580,7 @@ def get_output_var_names(self): """ return self._output_var_names - # ------------------------------------------------------------ - def get_component_name(self): + def get_component_name(self) -> str: """Get the name of the component. This method retrieves the model name using the `get_attribute` method. @@ -637,8 +589,7 @@ def get_component_name(self): """ return self.get_attribute("model_name") - # ------------------------------------------------------------ - def get_input_item_count(self): + def get_input_item_count(self) -> int: """Get the count of input variables. This method returns the total number of input variables defined in the model. @@ -647,8 +598,7 @@ def get_input_item_count(self): """ return len(self._input_var_names) - # ------------------------------------------------------------ - def get_output_item_count(self): + def get_output_item_count(self) -> int: """Get the count of output variables. This method returns the total number of output variables defined in the model. @@ -657,7 +607,6 @@ def get_output_item_count(self): """ return len(self._output_var_names) - # ------------------------------------------------------------ def get_value(self, var_name: str, dest: NDArray[Any]) -> NDArray[Any]: """Copy the values of a variable into the provided destination array. @@ -710,7 +659,6 @@ def get_value(self, var_name: str, dest: NDArray[Any]) -> NDArray[Any]: return dest - # ------------------------------------------------------------------- def get_value_ptr(self, var_name: str) -> NDArray[Any]: """Get a reference to the values of a variable. @@ -782,7 +730,7 @@ def get_value_ptr(self, var_name: str) -> NDArray[Any]: # Ensure dtype is float64 (C double), except for CAT-ID if var_name == "CAT-ID": - return arr # allow CAT-ID to pass on whatever the dtype is based on the input data + return arr # allow CAT-ID to pass on whatever the dtype is based on the input data elif arr.dtype != np.float64: LOG.warning( f"[BMI] Array for '{var_name}' has dtype {arr.dtype}, expected float64; converting." @@ -807,12 +755,7 @@ def get_value_ptr(self, var_name: str) -> NDArray[Any]: # LOG.debug(f"[BMI get_value_ptr] Returning ravelled array for variable '{var_name}'") return arr.ravel() - # ------------------------------------------------------------------- - # ------------------------------------------------------------------- - # BMI: Variable Information Functions - # ------------------------------------------------------------------- - # ------------------------------------------------------------------- - def get_var_name(self, long_var_name): + def get_var_name(self, long_var_name: str) -> str: """Get the short name of the variable corresponding to the long variable name. :param long_var_name: The long variable name as defined in the model. @@ -820,8 +763,7 @@ def get_var_name(self, long_var_name): """ return self._var_name_map_long_first[long_var_name] - # ------------------------------------------------------------------- - def get_var_units(self, long_var_name): + def get_var_units(self, long_var_name: str) -> str: """Get the units of the variable corresponding to the long variable name. :param long_var_name: The long variable name as defined in the model. @@ -829,7 +771,6 @@ def get_var_units(self, long_var_name): """ return self._var_units_map[long_var_name] - # ------------------------------------------------------------------- def get_var_type(self, var_name: str) -> str: """Get the data type of a variable. @@ -839,8 +780,7 @@ def get_var_type(self, var_name: str) -> str: """ return str(self.get_value_ptr(var_name).dtype) - # ------------------------------------------------------------ - def get_var_grid(self, name): + def get_var_grid(self, name: str) -> int: """Get the grid associated with a variable. :param name: The name of the variable. @@ -861,8 +801,7 @@ def get_var_grid(self, name): return self._var_grid_id raise (UnknownBMIVariable(f"No known variable in BMI model: {name}")) - # ------------------------------------------------------------ - def get_var_itemsize(self, name): + def get_var_itemsize(self, name: str) -> int: """Get the item size (in bytes) of a variable. This function retrieves the memory size (in bytes) for each element of the variable @@ -873,8 +812,7 @@ def get_var_itemsize(self, name): """ return self.get_value_ptr(name).itemsize - # ------------------------------------------------------------ - def get_var_location(self, name): + def get_var_location(self, name: str) -> str: """Get the location of a variable in the grid. This function determines the location of a variable (whether it's at a "face" @@ -893,8 +831,7 @@ def get_var_location(self, name): else: raise ValueError(f"get_var_location: grid_id {self._var_grid_id} unknown") - # ------------------------------------------------------------------- - def get_var_rank(self, long_var_name): + def get_var_rank(self, long_var_name: str) -> np.int16: """Get the rank of a variable. This function retrieves the rank (number of dimensions) of a variable @@ -906,7 +843,6 @@ def get_var_rank(self, long_var_name): """ return np.int16(0) - # ------------------------------------------------------------------- def get_start_time(self) -> float: """Get the model's start time. @@ -917,8 +853,6 @@ def get_start_time(self) -> float: """ return self._start_time - # ------------------------------------------------------------------- - def get_end_time(self) -> float: """Get the model's end time. @@ -930,8 +864,6 @@ def get_end_time(self) -> float: """ return self._end_time - # ------------------------------------------------------------------- - def get_current_time(self) -> float: """Get the current time of the model. @@ -942,7 +874,6 @@ def get_current_time(self) -> float: """ return self._values["current_model_time"] - # ------------------------------------------------------------------- def get_time_step(self) -> float: """Get the model's time step size. @@ -953,7 +884,6 @@ def get_time_step(self) -> float: """ return self._values["time_step_size"] - # ------------------------------------------------------------------- def get_time_units(self) -> str: """Get the units of time for the model. @@ -964,8 +894,6 @@ def get_time_units(self) -> str: """ return self.get_attribute("time_units") - # ------------------------------------------------------------------- - def set_value(self, var_name: str, values: NDArray[Any]): """Set model values for the provided BMI variable. @@ -981,7 +909,6 @@ def set_value(self, var_name: str, values: NDArray[Any]): else: self._values[var_name][:] = values - # ------------------------------------------------------------ def set_value_at_indices( self, var_name: str, indices: NDArray[np.int_], src: NDArray[Any] ): @@ -999,7 +926,6 @@ def set_value_at_indices( bmi_var_value_index = indices[i] self.get_value_ptr(var_name)[bmi_var_value_index] = src[i] - # ------------------------------------------------------------ def get_var_nbytes(self, var_name) -> int: """Get the number of bytes required for a variable. @@ -1011,7 +937,6 @@ def get_var_nbytes(self, var_name) -> int: """ return self.get_value_ptr(var_name).nbytes - # ------------------------------------------------------------ def get_value_at_indices( self, var_name: str, dest: NDArray[Any], indices: NDArray[np.int_] ) -> NDArray[Any]: @@ -1034,7 +959,6 @@ def get_value_at_indices( # JG Note: remaining grid funcs do not apply for type 'scalar' # Yet all functions in the BMI must be implemented # See https://bmi.readthedocs.io/en/latest/bmi.best_practices.html - # ------------------------------------------------------------ def get_grid_edge_count(self, grid_id: int) -> int: """Retrieve the number of edges for the specified grid. @@ -1101,7 +1025,6 @@ def get_grid_edge_count(self, grid_id: int) -> int: # If no valid grid is found, raise an exception or handle accordingly. raise ValueError("No valid grid found to calculate edge count.") - # ------------------------------------------------------------ def get_grid_edge_nodes( self, grid_id: int, edge_nodes: NDArray[np.int_] ) -> NDArray[np.int_]: @@ -1165,7 +1088,6 @@ def get_grid_edge_nodes( raise Exception("Unexpected error in retrieving edge nodes") - # ------------------------------------------------------------ def get_grid_face_count(self, grid_id: int) -> int: """Retrieve the number of faces for the specified grid. @@ -1192,7 +1114,6 @@ def get_grid_face_count(self, grid_id: int) -> int: # If the loop doesn't return, raise an exception indicating grid ID not found. raise ValueError("Grid ID not found in _grids.") - # ------------------------------------------------------------ def get_grid_face_edges( self, grid_id: int, face_edges: NDArray[np.int_] ) -> NDArray[np.int_]: @@ -1258,7 +1179,6 @@ def get_grid_face_edges( # If the loop doesn't return, raise an exception indicating an unexpected error raise Exception("Unexpected error in retrieving face edges.") - # ------------------------------------------------------------ def get_grid_face_nodes( self, grid_id: int, face_nodes: NDArray[np.int_] ) -> NDArray[np.int_]: @@ -1297,7 +1217,6 @@ def get_grid_face_nodes( # If the loop doesn't return, raise an exception indicating an unexpected error raise Exception("Unexpected error in retrieving face nodes.") - # ------------------------------------------------------------ def get_grid_node_count(self, grid_id: int) -> int: """Retrieve the number of nodes for the specified grid. @@ -1325,7 +1244,6 @@ def get_grid_node_count(self, grid_id: int) -> int: # If the loop doesn't return within the for loop, raise an exception raise ValueError("Grid ID not found in _grids.") - # ------------------------------------------------------------ def get_grid_nodes_per_face( self, grid_id: int, nodes_per_face: NDArray[np.int_] ) -> NDArray[np.int_]: @@ -1358,7 +1276,6 @@ def get_grid_nodes_per_face( # If the loop doesn't return, raise an exception indicating an unexpected error raise Exception("Unexpected error in retrieving nodes per face.") - # ------------------------------------------------------------ def get_grid_origin( self, grid_id: int, origin: NDArray[np.float64] ) -> NDArray[np.float64]: @@ -1377,7 +1294,6 @@ def get_grid_origin( return origin raise ValueError(f"get_grid_origin: grid_id {grid_id} unknown") - # ------------------------------------------------------------ def get_grid_rank(self, grid_id: int) -> int: """Retrieve the rank of the specified grid. @@ -1392,7 +1308,6 @@ def get_grid_rank(self, grid_id: int) -> int: return grid.rank raise ValueError(f"get_grid_rank: grid_id {grid_id} unknown") - # ------------------------------------------------------------ def get_grid_shape(self, grid_id: int, shape: NDArray[np.int_]) -> NDArray[np.int_]: """Retrieve the shape (dimensions) of the specified grid. @@ -1409,7 +1324,6 @@ def get_grid_shape(self, grid_id: int, shape: NDArray[np.int_]) -> NDArray[np.in return shape raise ValueError(f"get_grid_shape: grid_id {grid_id} unknown") - # ------------------------------------------------------------ def get_grid_size(self, grid_id: int) -> int: """Retrieve the size (total number of elements) of the specified grid. @@ -1424,7 +1338,6 @@ def get_grid_size(self, grid_id: int) -> int: return grid.size raise ValueError(f"get_grid_size: grid_id {grid_id} unknown") - # ------------------------------------------------------------ def get_grid_spacing( self, grid_id: int, spacing: NDArray[np.float64] ) -> NDArray[np.float64]: @@ -1443,8 +1356,6 @@ def get_grid_spacing( return spacing raise ValueError(f"get_grid_spacing: grid_id {grid_id} unknown") - # ------------------------------------------------------------ - def get_grid_type(self, grid_id: int) -> str: """Retrieve the type of the specified grid. @@ -1459,7 +1370,6 @@ def get_grid_type(self, grid_id: int) -> str: return grid.type raise ValueError(f"get_grid_type: grid_id {grid_id} unknown") - # ------------------------------------------------------------ def get_grid_x(self, grid_id: int, x: NDArray[np.float64]) -> NDArray[np.float64]: """Retrieve the x-coordinates (longitude or grid points) for the specified grid. @@ -1479,7 +1389,6 @@ def get_grid_x(self, grid_id: int, x: NDArray[np.float64]) -> NDArray[np.float64 return x raise ValueError(f"get_grid_x: grid_id {grid_id} unknown") - # ------------------------------------------------------------ def get_grid_y(self, grid_id: int, y: NDArray[np.float64]) -> NDArray[np.float64]: """Retrieve the y-coordinates (latitude or grid points) for the specified grid. @@ -1499,7 +1408,6 @@ def get_grid_y(self, grid_id: int, y: NDArray[np.float64]) -> NDArray[np.float64 return y raise ValueError(f"get_grid_y: grid_id {grid_id} unknown") - # ------------------------------------------------------------ def get_grid_z(self, grid_id: int, z: NDArray[np.float64]) -> NDArray[np.float64]: """Retrieve the z-coordinates (depth or grid points) for the specified grid. @@ -1519,12 +1427,6 @@ def get_grid_z(self, grid_id: int, z: NDArray[np.float64]) -> NDArray[np.float64 return z raise ValueError(f"get_grid_z: grid_id {grid_id} unknown") - # ------------------------------------------------------------ - # ------------------------------------------------------------ - # -- Random utility functions - # ------------------------------------------------------------ - # ------------------------------------------------------------ - def parse_config(cfg: dict) -> dict: """Parse the provided configuration dictionary (`cfg`) and modifies it based on certain rules. @@ -1630,12 +1532,18 @@ class NWMv3_Forcing_Engine_BMI_model_Gridded(NWMv3_Forcing_Engine_BMI_model_Base geospatial data and forcing inputs for the model simulation. """ - def __init__(self): + def __init__( + self, + config_file: str, + b_date: str = None, + geogrid: str = None, + output_path: str = None, + ): """Create a model that is ready for initialization. Initializes the model with default values for time, variables, and grid types. """ - super().__init__() + super().__init__(config_file, b_date, geogrid, output_path) self.GeoMeta = GriddedGeoMeta def grid_ranks(self) -> list[int]: @@ -1696,12 +1604,17 @@ class NWMv3_Forcing_Engine_BMI_model_HydroFabric(NWMv3_Forcing_Engine_BMI_model_ geospatial data and forcing inputs for the model simulation. """ - def __init__(self): + def __init__( + self, + b_date: str = None, + geogrid: str = None, + output_path: str = None, + ): """Create a model that is ready for initialization. Initializes the model with default values for time, variables, and grid types. """ - super().__init__() + super().__init__(b_date, geogrid, output_path) self.GeoMeta = HydrofabricGeoMeta def grid_ranks(self) -> list[int]: @@ -1758,12 +1671,18 @@ class NWMv3_Forcing_Engine_BMI_model_Unstructured(NWMv3_Forcing_Engine_BMI_model geospatial data and forcing inputs for the model simulation. """ - def __init__(self): + def __init__( + self, + config_file: str, + b_date: str = None, + geogrid: str = None, + output_path: str = None, + ): """Create a model that is ready for initialization. Initializes the model with default values for time, variables, and grid types. """ - super().__init__() + super().__init__(config_file, b_date, geogrid, output_path) self.GeoMeta = UnstructuredGeoMeta def grid_ranks(self) -> list[int]: diff --git a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/config.py b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/config.py index 17bb9f8b..cd58e24d 100755 --- a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/config.py +++ b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/config.py @@ -1,14 +1,20 @@ +from __future__ import annotations + import configparser import json import logging import os import re -import uuid from datetime import datetime, timedelta, timezone # Use the Error, Warning, and Trapping System Package for logging import numpy as np +from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core import mpi_utils +from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.consts import ( + CONFIGOPTIONS, + FORCINGINPUTMOD, +) from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.err_handler import ( err_out_screen, ) @@ -16,125 +22,37 @@ calculate_lookback_window, ) -from . import mpi_utils - LOG = logging.getLogger("FORCING") -FORCE_COUNT = 27 class ConfigOptions: """Configuration abstract class for configuration options read in from the file specified by the user.""" - def __init__(self, config: dict, b_date=None, geogrid_arg=None): + def __init__(self, cfg_bmi: dict, b_date: str = None, geogrid: str = None) -> None: """Initialize the configuration class to empty None attributes. - param config: The user-specified path to the configuration file. + The attributes of this class are populated by the validate_config function, which reads in the configuration file and checks that all necessary options are provided and properly formatted. The attributes of this class are used to control the flow of the program and the processing of input forcings. + + Args: + cfg_bmi (dict): The configuration dictionary read in from the configuration file specified by the user. This should be read in using the config_utils.read_config function, which also handles any necessary preprocessing of the configuration file. + b_date (str, optional): The beginning date of processing in the format YYYYMMDDHHMM. This is used to calculate the processing window for realtime simulations. If not provided, it will be read from the configuration file. + geogrid (str, optional): The filepath to the geogrid file to be used for processing. This is used to specify the grid information for regridding input forcings. If not provided, it will be read from the configuration file. + """ - self.bmi_time = None - self.current_time = None - self.bmi_time_index = 0 - self.input_forcings = None - self.precip_only_flag = False - self.supp_precip_forcings = None - self.input_force_dirs = None - self.input_force_types = None - self.supp_precip_dirs = None - self.supp_precip_file_types = None - self.supp_precip_param_dir = None - self.input_force_mandatory = None - self.supp_precip_mandatory = None - self.supp_pcp_max_hours = None - self.number_inputs = None - self.number_supp_pcp = None - self.number_custom_inputs = 0 - self.output_freq = None - self.sub_output_hour = None - self.sub_output_freq = None - self.scratch_dir = None - self.useCompression = 0 - self.useFloats = 0 - self.num_output_steps = None - self.num_supp_output_steps = None - self.actual_output_steps = None - self.realtime_flag = None - self.refcst_flag = None - self.ana_flag = None + self.cfg_bmi = cfg_bmi + if geogrid is not None: + self.user_provided_geogrid_flag = True + else: + self.user_provided_geogrid_flag = False + self.b_date_proc = b_date - self.e_date_proc = None - self.first_fcst_cycle = None - self.current_fcst_cycle = None - self.current_output_step = None - self.cycle_length_minutes = None - self.prev_output_date = None - self.current_output_date = None - self.look_back = None - self.future_time = None - self.fcst_freq = None - self.nFcsts = None - self.fcst_shift = None - self.fcst_input_horizons = None - self.fcst_input_offsets = None - self.process_window = None - self.spatial_meta = None - self.grid_type = None - self.grid_meta = None - self.ExactExtract = None - self.lat_var = None - self.lon_var = None - self.hgt_var = None - self.cosalpha_var = None - self.sinalpha_var = None - self.slope_var = None - self.slope_azimuth_var = None - self.slope_var_elem = None - self.slope_azimuth_var_elem = None - self.nodecoords_var = None - self.elemcoords_var = None - self.elemconn_var = None - self.numelemconn_var = None - self.element_id_var = None - self.hgt_elem_var = None - self.ignored_border_widths = None - self.regrid_opt = None - self.weightsDir = None - self.regrid_opt_supp_pcp = None - self.config_path = config - self.errMsg = None - self.statusMsg = None - self.logFile = None - self.logHandle = None - self.dScaleParamDirs = None - self.paramFlagArray = None - self.forceTemoralInterp = None - self.suppTemporalInterp = None - self.t2dDownscaleOpt = None - self.swDownscaleOpt = None - self.psfcDownscaleOpt = None - self.precipDownscaleOpt = None - self.q2dDownscaleOpt = None - self.t2BiasCorrectOpt = None - self.psfcBiasCorrectOpt = None - self.q2BiasCorrectOpt = None - self.windBiasCorrect = None - self.swBiasCorrectOpt = None - self.lwBiasCorrectOpt = None - self.precipBiasCorrectOpt = None - self.runCfsNldasBiasCorrect = False - self.cfsv2EnsMember = None - self.customSuppPcpFreq = None - self.customFcstFreq = None - self.rqiMethod = None - self.rqiThresh = 1.0 + + self.geogrid = geogrid + + self.bmi_time_index = 0 self.globalNdv = -9999.0 self.d_program_init = datetime.now(timezone.utc) self.errFlag = 0 - self.nwmVersion = None - self.nwmConfig = None - self.include_lqfrac = False - self.forcing_output = None - self.aws = None - self.aws_obj = None - self.aws_time = None self.aorc_conus_source = "s3://noaa-nws-aorc-v1-1-1km" self.aorc_conus_year_url = "{source}/{year}.zarr" self.aorc_alaska_source = "s3://ngwpc-data/AORC/Alaska" @@ -143,19 +61,233 @@ def __init__(self, config: dict, b_date=None, geogrid_arg=None): ) self.nwm_source = "s3://noaa-nwm-retrospective-3-0-pds" - self.nwm_geogrid = None - self.geogrid = geogrid_arg - self.geopackage = None + self._scratch_dir_has_been_uniquefied = False + self.supp_precip_forcings = self.extract_input_variable("SuppPcp") + if not self.precip_only_flag: + self.input_forcings = self.extract_input_variable("InputForcings") + + # Create temporary array to hold flags if we need input parameter files. + self.param_flag = np.zeros([len(self.input_forcings)], int) - self.uid64 = None + # set list of attibutes from consts.py to None. + # These are indexed from the consts dictionary using the class name + for attr in CONFIGOPTIONS[self.__class__.__name__]: + setattr(self, attr, None) self.broadcast_new_64bit_uid() - self._scratch_dir_has_been_uniquefied = False + for ( + cfg_bmi_attr, + config_options_attr, + ) in self.try_config_get_except_attr_map.items(): + setattr(self, config_options_attr, self.try_config_get(cfg_bmi_attr)) + + self.set_attrs(CONFIGOPTIONS["extract_input_variable_attrs_map"]) + + if self.precip_only_flag: + self.set_attrs( + CONFIGOPTIONS["extract_input_variable_attrs_map_precip_only"] + ) + self.set_attrs( + CONFIGOPTIONS["extract_input_variable_attrs_map_not_precip_only"], + set_none=True, + ) + else: + self.set_attrs( + CONFIGOPTIONS["extract_input_variable_attrs_map_not_precip_only"] + ) + self.set_attrs( + CONFIGOPTIONS["extract_input_variable_attrs_map_precip_only"], + set_none=True, + ) + if 27 in self.input_forcings: + self.nwm_geogrid = self.extract_input_variable("NWM_Geogrid") + + if self.perform_downscaling: + self.set_attrs(CONFIGOPTIONS["downscaling_attrs_map"]) + if self.grid_type == "unstructured": + self.set_attrs(CONFIGOPTIONS["downscaling_unstructred_attrs_map"]) + + for cfg_bmi_attr, config_options_attr in CONFIGOPTIONS[ + "extract_input_variable_set_default_attrs_map" + ].items(): + if config_options_attr in ["supp_pcp_max_hours", "weightsDir"]: + default = None + else: + default = 0 + setattr( + self, + config_options_attr, + self.extract_input_variable_set_default(cfg_bmi_attr, default), + ) + + if self.realtime_flag: + calculate_lookback_window(self) + if self.look_back != -9999: + calculate_lookback_window(self) + + @property + def try_config_get_except_attr_map(self) -> dict: + """Get the mapping of configuration variable names to class attribute names for variables that are extracted directly from the configuration file without any additional processing. This is used to control how variables are extracted from the configuration file and assigned to class attributes in a consistent way based on the mapping specified in the consts.py file.""" + dict_map = CONFIGOPTIONS["try_config_get_except_attr_map"] + # if self._b_date_proc is not None and "RefcstBDateProc" in dict_map: + # dict_map.pop("RefcstBDateProc") + if self.geogrid is not None and "GeogridIn" in dict_map: + dict_map.pop("GeogridIn") + return dict_map + + @property + def cfg_bmi(self) -> dict: + """Return the configuration dictionary read in from the configuration file specified by the user.""" + return self._cfg_bmi + + @cfg_bmi.setter + def cfg_bmi(self, value: dict) -> None: + """Set the configuration dictionary read in from the configuration file specified by the user.""" + if not isinstance(value, dict): + raise TypeError( + f"Expected dict, got {type(value)} for type of cfg_bmi: {value}" + ) + self._cfg_bmi = value + + @property + def force_count(self) -> int: + """Calculate the number of total possible input forcing options based on the length of the InputForcings list in the consts.py file. This is used for error checking to ensure users specify valid input forcing options in the configuration file.""" + return len(FORCINGINPUTMOD["PRODUCT_NAME"]) + + @property + def supp_precip_count(self) -> int: + """Calculate the number of total possible supplemental precip forcing options based on the length of the SuppPrecipForcings list in the consts.py file. This is used for error checking to ensure users specify valid supplemental precip forcing options in the configuration file.""" + # TODO make this dynamic based on the length of the SUPPPRECIPMOD list in consts.py, but for now hardcoding to 15 since that is the number of options currently available in consts.py and this will avoid any issues with the formatting of the consts.py file causing errors in the program. This is used for error checking to ensure users specify valid supplemental precip forcing options in the configuration file. + # return len(SUPPPRECIPMOD["suppPrecipMod"]["PRODUCT_NAMES"]) + return 15 + + @property + def precip_only_flag(self) -> bool: + """Flag to indicate whether the user has chosen to run the supplemental precip forcings module only, which will trigger some different processing pathways and error checking for certain configuration options.""" + precip_only = False + if self.number_supp_pcp == 1: + if int(self.supp_precip_forcings[0]) == 14: + precip_only = True + return precip_only + + def set_attrs(self, attrs_dict: dict, set_none: bool = False): + """Set the attributes of the class based on the configuration file. This is used to populate the attributes of the class after they have been read in and validated from the configuration file.""" + for cfg_bmi_attr, config_options_attr in attrs_dict.items(): + if set_none: + attr = None + else: + attr = self.extract_input_variable(cfg_bmi_attr) + setattr(self, config_options_attr, attr) + + def set_attrs_use_default(self, attrs_dict: dict): + """Set the attributes of the class based on the configuration file. Set default value to default if not found in config file.""" + for cfg_bmi_attr, config_options_attr in attrs_dict.items(): + setattr( + self, + config_options_attr, + self.extract_input_variable_set_default(cfg_bmi_attr), + ) + + def extract_input_variable(self, variable_name: str) -> str: + """Extract the variable name from the configuration file for a given variable.""" + try: + return self.cfg_bmi[variable_name] + except ValueError as e: + err_out_screen( + f"Improper {variable_name} value specified in the configuration file. Error: {e}" + ) + except (KeyError, configparser.NoOptionError) as e: + err_out_screen( + f"Unable to locate {variable_name} in the configuration file. Error: {e}" + ) + except json.decoder.JSONDecodeError as e: + err_out_screen( + f"Improper {variable_name} file option specified in configuration file. Error: {e}", + e, + ) + + def extract_input_variable_set_default(self, variable_name: str, default=0) -> str: + """Extract the variable name from the configuration file for a given variable, and set it to a default value if it is not found.""" + try: + variable = self.cfg_bmi[variable_name] + except (KeyError, configparser.NoOptionError) as e: + variable = default + except ValueError as e: + err_out_screen( + f"Improper {variable_name} value: {self.cfg_bmi[variable_name]}", e + ) + if default == 0: + if variable not in [0, 1]: + err_out_screen(f"Please choose a {variable_name} value of 0 or 1.") + return variable + + def try_config_get(self, variable_name: str) -> str: + """Try to get a variable from the configuration file, and return a default value if it is not found.""" + try: + var = self.cfg_bmi.get(variable_name) + if var is None: + err_out_screen( + f"Unable to locate {variable_name} in the configuration file." + ) + return var + except (KeyError, configparser.NoOptionError) as e: + err_out_screen( + f"Unable to locate {variable_name} in the configuration file.", e + ) + + def check_number_of_inputs( + self, value: list, variable_name: str, input_type: str, number_inputs: int + ) -> None: + """Check that the number of inputs specified by the user in the configuration file matches the expected number of inputs for a given variable.""" + if len(value) != number_inputs: + err_out_screen( + f"Number of {variable_name} values must match the number of {input_type} in the configuration file." + ) + + def check_number_of_inputs_forcings(self, value: list, variable_name: str) -> None: + """Check that the number of inputs specified by the user in the configuration file matches the expected number of inputs for a given variable, specifically for input forcings variables which should match the number of input forcing options specified by the user in the configuration file.""" + return self.check_number_of_inputs( + value, variable_name, " InputForcings", self.number_inputs + ) + + def check_number_of_inputs_supp_pcp(self, value: list, variable_name: str) -> None: + """Check that the number of inputs specified by the user in the configuration file matches the expected number of inputs for a given variable, specifically for supplemental precip forcing variables which should match the number of supplemental precip forcing options specified by the user in the configuration file.""" + return self.check_number_of_inputs( + value, variable_name, " SupplementalPrecipForcings", self.number_supp_pcp + ) + + def check_input_values_in_range( + self, value: list, variable_name: str, valid_input_options: list + ) -> None: + """Check that the input values specified by the user in the configuration file are within a valid range for a given variable.""" + for val in value: + if val not in valid_input_options: + err_out_screen( + f"Invalid {variable_name} value '{val}' specified in configuration file. Please specify valid values: {valid_input_options}." + ) + + def check_input_values_non_negative(self, value: list, variable_name: str) -> None: + """Check that the input values specified by the user in the configuration file are positive for a given variable.""" + for val in value: + if float(val) < 0: + err_out_screen( + f"Invalid {variable_name} value '{val}' specified in configuration file. Please specify values greater than or equal to zero." + ) + + def check_input_values_positive(self, value: list, variable_name: str) -> None: + """Check that the input values specified by the user in the configuration file are positive for a given variable.""" + for val in value: + if val <= 0: + err_out_screen( + f"Invalid {variable_name} value '{val}' specified in configuration file. Please specify values greater than zero." + ) def uniquefy_scratch_dir_as_child(self, uid: str) -> None: """Modify the existing scratch dir by adding the UID string available to all ranks from the MpiConfig class. + This may only be called once. Subsequent calls will result in an error. - This must be called by all ranks, once.""" + This must be called by all ranks, once. + """ LOG.debug(f"Uniquefying scratch dir: adding suffix {uid} to {self.scratch_dir}") if not isinstance(uid, str): raise TypeError(f"Expected str, got {type(uid)} for type of uid: {uid}") @@ -167,223 +299,402 @@ def uniquefy_scratch_dir_as_child(self, uid: str) -> None: ) self.scratch_dir = os.path.join(self.scratch_dir, uid) self._scratch_dir_has_been_uniquefied = True - self.make_scratch_dir() - def make_scratch_dir(self) -> None: + def make_scratch_dir(self, scratch_dir: str) -> None: """Make the scratch dir and its parents.""" - os.makedirs(self.scratch_dir, exist_ok=True) - LOG.debug(f"Scratch dir: {self.scratch_dir}") + os.makedirs(scratch_dir, exist_ok=True) + LOG.debug(f"Scratch dir: {scratch_dir}") - def broadcast_new_64bit_uid(self): + def broadcast_new_64bit_uid(self) -> None: """Broadcast a random uint64 then save the hash of that to self.uid64, which effectively broadcasts the same unique string to all ranks. - Should be called once to avoid confusion.""" + + Should be called once to avoid confusion. + """ if self.uid64 is not None: raise RuntimeError("self.uid64 has already been initialized.") self.uid64 = mpi_utils.get_new_broadcasted_uid() - def validate_config(self, cfg_bmi: dict) -> None: - """Validate in options from the configuration file and check that proper options were provided.""" - # Ensure b_date_proc is set; if not, read from the configuration file - if self.b_date_proc is None: - try: - self.b_date_proc = cfg_bmi.get( - "RefcstBDateProc", None - ) # Default to None if not found - if self.b_date_proc is None: - err_out_screen( - "Unable to locate RefcstBDateProc under Logistics section in configuration file." - ) - except KeyError as e: - err_out_screen( - "Unable to locate RefcstBDateProc under Logistics section in configuration file.", - e, - ) + @property + def supp_precip_forcings(self): + """Choose a set of supplemental precipitation file(s) to layer into the final LDASIN forcing files processed from the options above. The following is a mapping of numeric values to external input native forcing files. + + 1. MRMS GRIB2 hourly radar-only QPE + 2. MRMS GRIB2 hourly gage-corrected radar QPE + 3. WRF-ARW 2.5 km 48-hr Hawaii nest precipitation. + 4. WRF-ARW 2.5 km 48-hr Puerto Rico nest precipitation. + 5. CONUS MRMS GRIB2 hourly MultiSensor QPE (Pass 2 or Pass 1) + 6. Hawaii MRMS GRIB2 hourly MultiSensor QPE (Pass 2 or Pass 1) + 7. MRMS SBCv2 Liquid Water Fraction (netCDF only) + 8. NBM Conus MR + 9. NBM Alaska MR + 10. Alaska MRMS (no liquid water fraction) + 11. Alaska Stage IV NWS Precip + 12. CONUS Stage IV NWS Precip + 13. MRMS PrecipFlag precipitation classification file + 14. Custom Frequency Supplementary Precipitation product (sub-hourly precip) + 15. NBM Puerto Rico + 16. NBM Hawaii + - Example- SuppPcp: [1, 5, 13] + """ + return self._supp_precip_forcings + + @supp_precip_forcings.setter + def supp_precip_forcings(self, value: list) -> None: + """Set the list of supplemental precip forcing options specified by the user in the configuration file. This is used to control which supplemental precip forcings are processed and how they are processed based on the other configuration options specified for each supplemental precip forcing.""" + if len(value) > 0: + self.check_input_values_in_range( + [int(i) for i in value], + "SuppPcp", + list(range(1, self.supp_precip_count + 1)), + ) + self._supp_precip_forcings = value - # Ensure geopackage is set; if not, read from the configuration file - if self.geopackage is None: - try: - self.geopackage = cfg_bmi.get( - "Geopackage", None - ) # Default to None if not found - if self.geopackage is None: - err_out_screen( - "Unable to locate Geopackage in the configuration file." - ) - except KeyError as e: - err_out_screen( - "Unable to locate Geopackage in the configuration file.", e - ) + @property + def output_freq(self) -> int: + """Get the output frequency in minutes specified by the user in the configuration file. This is used to control the output frequency of the processed forcings, and is necessary for both realtime and reforecast simulations.""" + return self._output_freq - # Ensure geogrid is set; if not, read from the configuration file - if self.geogrid is None: - try: - geogrid_base = cfg_bmi.get( - "GeogridIn", None - ) # Default to None if not found - except KeyError as e: - err_out_screen( - "Unable to locate GeogridIn in the configuration file.", e - ) - if geogrid_base is None: - err_out_screen("Unable to locate GeogridIn in the configuration file.") - self.geogrid = None - else: - geogrid_parent = os.path.dirname(geogrid_base) - geogrid_filename = os.path.basename(geogrid_base) - if self.uid64 is None: - raise ValueError("self.uid64 cannot be None, please initialize it.") - self.geogrid = os.path.join( - geogrid_parent, f"{self.uid64}_{geogrid_filename}" - ) - # Create directory for esmf_mesh file - if not os.path.isdir(geogrid_parent): - try: - os.makedirs(geogrid_parent, exist_ok=True) - LOG.debug(f"Created esmf mesh directory: {geogrid_parent}") - except OSError as e: - err_out_screen( - f"Unable to create esmf_mesh directory: {geogrid_parent}. Error: {e}" - ) + @output_freq.setter + def output_freq(self, value: int) -> None: + """Specify the output frequency in minutes. Note that any frequencies at higher intervals than what if provided as input will entail input forcing data being temporally interpolated. - # Read in the base input forcing options as an array of values to map. - try: - self.supp_precip_forcings = cfg_bmi["SuppPcp"] - except KeyError as e: + Example- OutputFrequency: 60 + """ + self.check_input_values_non_negative([value], "OutputFrequency") + self._output_freq = value + + @property + def sub_output_hour(self) -> int: + """Get the sub-daily output hour specified by the user in the configuration file. This is used to control the output frequency of the processed forcings for sub-daily output frequencies, and is only necessary if the user has chosen a sub-daily output frequency in the configuration file.""" + return self._sub_output_hour + + @sub_output_hour.setter + def sub_output_hour(self, value: int) -> None: + """Sub output hour. + + New variable currently for NWMv3.1 operations to properly ingest GFS 13km forecast data that outputs various frequencies throughout the forecast cycle lifetime. This variable will properly account for reading time slices of the forecast cycle. Currently only needed for GFS 13km operational configuration. Otherwise, set this value to 0. + + Example- SubOutputHour: 0 + """ + self.check_input_values_non_negative([value], "SubOutputHour") + if value == 0: + value = None + self._sub_output_hour = value + + @property + def sub_output_freq(self) -> int: + """Calculate the sub-daily output frequency in minutes based on the output frequency and sub-daily output hour specified by the user in the configuration file. This is used to control the output frequency of the processed forcings for sub-daily output frequencies, and is only necessary if the user has chosen a sub-daily output frequency in the configuration file.""" + return self._sub_output_freq + + @sub_output_freq.setter + def sub_output_freq(self, value: int) -> None: + """Sub output frequency. + + New variable currently for NWMv3.1 operations to properly ingest GFS 13km forecast data that outputs various frequencies throughout the forecast cycle lifetime. This variable will properly account for reading time slices of the forecast cycle. Currently only needed for GFS 13km operational configuration. Otherwise, set this value to 0. + + Example- SubOutputFreq: 0 + """ + if value < 0: err_out_screen( - "Unable to locate SuppPcp under SuppForcing section in configuration file.", - e, + "Please specify an SubOutFreq that is greater than zero minutes." ) - except configparser.NoOptionError as e: + if value == 0: + value = None + self._sub_output_freq = value + + @property + def scratch_dir(self) -> str: + """Specify a scratch directory that will be used for storage of temporary files. These files will be removed automatically by the program. at the end of the BMI instance. However, this directory will also store the output forcing file if requested by the user as well (will not be deleted in this instance). + + Example- ScratchDir: "./ScratchDir + """ + return self._scratch_dir + + @scratch_dir.setter + def scratch_dir(self, value: str) -> None: + """Set the pathway to the scratch directory specified by the user in the configuration file. This is used to control where intermediate files are written during processing, and is necessary for both realtime and reforecast simulations.""" + self.make_scratch_dir(value) + self._scratch_dir = value + + @property + def useCompression(self) -> int: + """Flag to activate scale_factor / add_offset byte packing in the output files. 0 - Deactivate compression 1 - Activate compression, Only applicable in this instance when you request a netcdf output forcing file (Output: 1). Otherwise, just set to 0. + + Example- compressOutput: 0 + """ + return self._useCompression + + @useCompression.setter + def useCompression(self, value: int) -> None: + """Set the flag for whether to use compression when writing output files specified by the user in the configuration file. This is used to control whether output files are compressed, which can save disk space but may increase processing time.""" + if value is None: + value = 0 + self.check_input_values_in_range([value], "compressOutput", [0, 1]) + self._useCompression = value + + @property + def ana_flag(self) -> int: + """If this is AnA run, set AnAFlag to 1, otherwise 0. Setting this flag will change the behavior of some Bias Correction routines as the ForecastInputOffsets options. + + Example- AnAFlag: 1 + """ + return self._ana_flag + + @ana_flag.setter + def ana_flag(self, value: int) -> None: + """Set the flag for whether to include the analysis time step in the output files specified by the user in the configuration file. This is used to control whether the analysis time step is included in the output files, which can be useful for certain applications but may not be necessary for all users.""" + value = int(value) + self.check_input_values_in_range([value], "AnAFlag", [0, 1]) + self._ana_flag = value + + @property + def look_back(self) -> int: + """Specify a lookback period in minutes to process data. This is required if you are only processing an AnA operational configuration. This value should specify how far back you need to look in time from your "RefcstBDateProc" start date that you specified. In this instance, that start date will be your actual end date. If no LookBack specified, please specify -9999. + + Example- LookBack: 180 + """ + return self._look_back + + @look_back.setter + def look_back(self, value: int) -> None: + """Set the look back window in hours specified by the user in the configuration file. This is used to calculate the processing window for reforecast simulations, and is only necessary if the user is running a reforecast simulation with a specified processing window rather than a realtime simulation.""" + if value <= 0 and value != -9999: + err_out_screen("Please specify a positive LookBack or -9999 for realtime.") + self._look_back = value + + @property + def fcst_freq(self) -> int: + """Specify a forecast frequency in minutes. This value specifies how often to generate a set of forecast forcings. If generating hourly retrospective forcings, specify this value to be 60. + + Example- ForecastFrequency: 60 + """ + return self._fcst_freq + + @fcst_freq.setter + def fcst_freq(self, value: int) -> None: + """Set the forecast frequency in hours specified by the user in the configuration file. This is used to calculate the processing window for reforecast simulations, and is only necessary if the user is running a reforecast simulation with a specified processing window rather than a realtime simulation.""" + self.check_input_values_non_negative([value], "ForecastFrequency") + if value > 1440: err_out_screen( - "Unable to locate SuppPcp under SuppForcing section in configuration file.", - e, + "Only forecast cycles of daily or sub-daily are supported at this time" ) - except json.decoder.JSONDecodeError as e: - err_out_screen("Improper SuppPcp option specified in configuration file", e) + self._fcst_freq = value - self.number_supp_pcp = len(self.supp_precip_forcings) + @property + def spatial_meta(self): + """Specify the optional land spatial metadata file. If found, coordinate projection information and coordinate will be translated from to the final output file. This variable is only a special case if the user is specifying the original WRF-Hydro domain from earlier NWM versions. Otherwise, just leave the one blank (''). - if self.number_supp_pcp == 1: - if int(self.supp_precip_forcings[0]) == 14: - self.precip_only_flag = True + Example- SpatialMetaIn: ./GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc + """ + return self._spatial_meta - if not self.precip_only_flag: - # Read in the base input forcing options as an array of values to map. - try: - self.input_forcings = cfg_bmi["InputForcings"] - except KeyError as e: - err_out_screen( - "Unable to locate InputForcings under Input section in configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate InputForcings under Input section in configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper InputForcings option specified in configuration file", e - ) - if len(self.input_forcings) == 0: + @spatial_meta.setter + def spatial_meta(self, value: str) -> None: + """Set the spatial metadata options specified by the user in the configuration file. This is used to control how spatial metadata is handled during processing, and is necessary for both realtime and reforecast simulations.""" + if len(value) == 0: + # No spatial metadata file found. + value = None + else: + if not os.path.isfile(value): err_out_screen( - "Please choose at least one InputForcings dataset to process" + f"Unable to locate optional spatial metadata file: {value}." ) - self.number_inputs = len(self.input_forcings) + self._spatial_meta = value - # Check to make sure forcing options make sense - for force_opt in self.input_forcings: - if force_opt < 0 or force_opt > FORCE_COUNT: - err_out_screen( - f"Please specify InputForcings values between 1 and {FORCE_COUNT}." - ) + @property + def b_date_proc(self) -> str: + """If running an operational configuration in realtime or just using a retrospective dataset (NWM, AORC, ERA5), this will be the defined start date for the NextGen Forcing Engine BMI which is assumed to be the beginning of the forecast cycle (i.e. hour 0) or just the start date of the retrospective dataset. From there the first time step will be hour 1 from the start date specified here. If you're running an AnA configuration however, this variable becomes the end date of the simulation and the "LookBack" value specified above will be how far back you look in time for the AnA operational configuration. - # Keep tabs on how many custom input forcings we have. - if force_opt == 10: - self.number_custom_inputs = self.number_custom_inputs + 1 - - # Flag to force mandatory configuration option to specify the NWM geogrid file if user requests - # NWM forcing files to be regridded to a given domain configuration - if force_opt == 27: - try: - self.nwm_geogrid = cfg_bmi["NWM_Geogrid"] - except KeyError as e: - err_out_screen( - "Unable to locate NWM Geogrid file required for the NWM forcings module. Need to specify the pathway to the NWM geo_em_DOMAIN.nc file to the NWM_Geogrid configuration input option within the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate NWM Geogrid file required for the NWM forcings module. Need to specify the pathway to the NWM geo_em_DOMAIN.nc file to the NWM_Geogrid configuration input option within the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper NWM Geogrid file option specified in configuration file", - e, - ) + Example- RefcstBDateProc: 202210071400 + """ + return self._b_date_proc - # Read in the input forcings types (GRIB[1|2], NETCDF) - try: - # self.input_force_types = config.get('Input', 'InputForcingTypes').strip("[]").split(',') - # self.input_force_types = [ftype.strip() for ftype in self.input_force_types] - self.input_force_types = cfg_bmi["InputForcingTypes"] - if self.input_force_types == [""]: - self.input_force_types = [] - except KeyError as e: + @b_date_proc.setter + def b_date_proc(self, value: str | datetime) -> None: + """Set the beginning date of processing for reforecast simulations. This is used to calculate the processing window for reforecast simulations.""" + if isinstance(value, datetime): + self._b_date_proc = value + elif value is None: + self._b_date_proc = self.try_config_get("RefcstBDateProc") + elif value != -9999: + if isinstance(value, str) and len(value) != 12: err_out_screen( - "Unable to locate InputForcingTypes in Input section in the configuration file.", - e, + "Improper RefcstBDateProc length entered into the configuration file. Please check your entry." ) - except configparser.NoOptionError as e: + try: + self._b_date_proc = datetime.strptime(value, "%Y%m%d%H%M") + except ValueError as e: err_out_screen( - "Unable to locate InputForcingTypes in Input section in the configuration file.", + "Improper RefcstBDateProc value entered into the configuration file. Please check your entry.", e, ) - if len(self.input_force_types) != self.number_inputs: - err_out_screen( - "Number of InputForcingTypes must match the number " - "of InputForcings in the configuration file." - ) - for file_type in self.input_force_types: - if file_type not in [ - "GRIB1", - "GRIB2", - "NETCDF", - "NETCDF4", - "NWM", - "ZARR", - "GRIB2_CFS", - ]: - err_out_screen( - f'Invalid forcing file type "{file_type}" specified. ' - "Only GRIB1, GRIB2, NETCDF, NWM, ZARR, and GRIB2_CFS are supported" - ) + else: + self._b_date_proc = -9999 + LOG.info(f"Begin date: {value}") + + @property + def realtime_flag(self) -> bool: + """Flag to indicate whether the user has chosen to run a realtime simulation, which will trigger some different processing pathways and error checking for certain configuration options, and will also control how the processing window is calculated.""" + if self.look_back == -9999: + value = False + elif self.b_date_proc == -9999: + value = True + else: + value = False + return value + + @property + def refcst_flag(self) -> bool: + """Flag to indicate whether the user has chosen to run a reforecast simulation, which will trigger some different processing pathways and error checking for certain configuration options, and will also control how the processing window is calculated.""" + if self.look_back == -9999: + return True + elif self.b_date_proc == -9999: + return True + else: + return False + + @property + def geopackage(self) -> str: + """Get the pathway to the geopackage file to be used for processing. This is used to specify the grid information for regridding input forcings, and is only necessary if the user is running a simulation that requires regridding of input forcings.""" + return self._geopackage - # Read in the input directories for each forcing option. + @geopackage.setter + def geopackage(self, value: str) -> None: + """Set the pathway to the geopackage file to be used for processing. This is used to specify the grid information for regridding input forcings, and is only necessary if the user is running a simulation that requires regridding of input forcings.""" + self._geopackage = value + + @property + def geogrid(self) -> str: + """Specify a geogrid file (e.g. latitude, longitude, mesh connectivity, elevation, slope) that defines domain to which the forcings are being processed to. + + Example- GeogridIn: ./geo_em_CONUS.nc + """ + return self._geogrid + + @geogrid.setter + def geogrid(self, value: str) -> None: + """Set the pathway to the geogrid file to be used for processing. This is used to specify the grid information for regridding input forcings, and is only necessary if the user is running a simulation that requires regridding of input forcings.""" + if self.user_provided_geogrid_flag: + self._geogrid = value + if value is None: + self._geogrid = value + # err_out_screen("Unable to locate GeogridIn in the configuration file.") + else: + geogrid_parent = os.path.dirname(value) + geogrid_filename = os.path.basename(value) + if self.uid64 is None: + raise ValueError("self.uid64 cannot be None, please initialize it.") + self._geogrid = os.path.join( + geogrid_parent, f"{self.uid64}_{geogrid_filename}" + ) + self.try_make_dir(geogrid_parent, " esmf_mesh") + + def try_make_dir(self, directory: str, optional_str: str = "") -> None: + """Try to make a directory, and catch any errors.""" + if not os.path.isdir(directory): try: - self.input_force_dirs = cfg_bmi["InputForcingDirectories"] - except KeyError as e: - err_out_screen( - "Unable to locate InputForcingDirectories in Input section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: + os.makedirs(directory, exist_ok=True) + LOG.debug(f"Created{optional_str} directory: {directory}") + except OSError as e: err_out_screen( - "Unable to locate InputForcingDirectories in Input section in the configuration file.", - e, + f"Unable to create{optional_str} directory: {directory}. Error: {e}" ) - if len(self.input_force_dirs) != self.number_inputs: + + @property + def input_forcings(self) -> list: + """Get the list of input forcing options specified by the user in the configuration file. This is used to control which input forcings are processed and how they are processed based on the other configuration options specified for each input forcing.""" + return self._input_forcings + + @input_forcings.setter + def input_forcings(self, value: list) -> None: + """Set the list of input forcing options specified by the user in the configuration file. This is used to control which input forcings are processed and how they are processed based on the other configuration options specified for each input forcing.""" + if not self.precip_only_flag: + self.check_input_values_in_range( + value, "InputForcings", list(range(1, self.force_count + 1)) + ) + self._input_forcings = value + + @property + def number_inputs(self) -> int: + """Calculate the number of input forcing options specified by the user in the configuration file. This is used for error checking to ensure users specify valid input forcing options in the configuration file, and to control the flow of the program based on how many input forcings are being processed.""" + if not self.precip_only_flag: + if len(self.input_forcings) == 0: err_out_screen( - "Number of InputForcingDirectories must match the number " - "of InputForcings in the configuration file." + "Please choose at least one InputForcings dataset to process" ) + return len(self.input_forcings) + + @property + def number_custom_inputs(self) -> int: + """Calculate the number of custom input forcing options specified by the user in the configuration file. This is used to control the flow of the program based on how many custom input forcings are being processed, since custom input forcings require some different processing pathways.""" + if not self.precip_only_flag: + count = 0 + for force_opt in self.input_forcings: + if force_opt == 10: + count += 1 + return count + else: + return 0 + + @property + def nwm_geogrid(self) -> str: + """Only for the NWM v3 retorspective forcing module option (27) that requires the geo_em_NWM_DOMAIN.nc file as input for the NextGen Forcings Engine to properly setup up the ESMF grid object for the NWM forcing files since that information is not readily available in the NWM v3 retrospective forcing files.""" + return self._nwm_geogrid + + @nwm_geogrid.setter + def nwm_geogrid(self, value: str) -> None: + """Set the pathway to the NWM geogrid file specified by the user in the configuration file. This is used to specify the grid information for regridding NWM input forcings, and is only necessary if the user has chosen to regrid NWM input forcings in the configuration file.""" + if not self.precip_only_flag and 27 in self.input_forcings: + self._nwm_geogrid = value + else: + self._nwm_geogrid = None + + @property + def input_force_types(self) -> list: + """Get the list of input forcing file types specified by the user in the configuration file. This is used to control how input forcings are read in and processed based on the file type specified for each input forcing in the configuration file.""" + return self._input_force_types + + @input_force_types.setter + def input_force_types(self, value: list) -> None: + """Specify the file type for each forcing (comma separated). Valid types are GRIB1, GRIB2, NETCDF, and NETCDF4. + + Example- InputForcingTypes: [GRIB2,GRIB2]\ + """ + if not self.precip_only_flag: + if value == [""]: + value = [] + self.check_number_of_inputs_forcings(value, "InputForcingTypes") + self.check_input_values_in_range( + value, "InputForcingTypes", self.file_types + ) + self._input_force_types = value + + @property + def file_types(self): + """Get the list of input forcing file types specified by the user in the configuration file. This is used to control how input forcings are read in and processed based on the file type specified for each input forcing in the configuration file.""" + return CONFIGOPTIONS["file_types"] + + @property + def input_force_dirs(self) -> list: + """Get the list of input forcing directories specified by the user in the configuration file. This is used to control where input forcings are read in from for each input forcing specified by the user in the configuration file.""" + if self._input_force_dirs: + return self._input_force_dirs + else: + None + + @input_force_dirs.setter + def input_force_dirs(self, value: list) -> None: + """Specify the input directories for each forcing product. If a user has the ability to connect to the AWS servers and they specify configuration #12 (CONUS AORC data) or configuration #27 (NWM retrospective forcing data) then this specific configuration input can be left as a blank string (""). + + Example- InputForcingDirectories: [./GFS,./NDFD] + """ + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "InputForcingDirectories") # Loop through and ensure all input directories exist. Also strip out any whitespace # or new line characters. - for dir_tmp in range(0, len(self.input_force_dirs)): - self.input_force_dirs[dir_tmp] = self.input_force_dirs[dir_tmp].strip() - - dir_path = self.input_force_dirs[dir_tmp] + for dir_tmp in range(0, len(value)): + value[dir_tmp] = value[dir_tmp].strip() + dir_path = value[dir_tmp] forcing_type = self.input_forcings[dir_tmp] is_aws_forcing = forcing_type in [12, 21, 27] @@ -391,1308 +702,575 @@ def validate_config(self, cfg_bmi: dict) -> None: if is_aws_forcing: self.aws = True else: - try: - os.makedirs(dir_path, exist_ok=True) - LOG.debug(f"Created missing forcing directory: {dir_path}") - except OSError as e: - err_out_screen( - f"Unable to create forcing directory: {dir_path}. Error: {e}" - ) + self.try_make_dir(dir_path, " forcing") + self._input_force_dirs = value - # Read in the mandatory enforcement options for input forcings. - try: - self.input_force_mandatory = cfg_bmi["InputMandatory"] - except KeyError as e: - err_out_screen( - "Unable to locate InputMandatory under Input section in configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate InputMandatory under Input section in configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper InputMandatory option specified in configuration file", e - ) + @property + def input_force_mandatory(self) -> list: + """Get the list of input forcing mandatory flags specified by the user in the configuration file. This is used to control whether the program should raise an error if input forcings for a given forecast cycle are not found for each input forcing specified by the user in the configuration file.""" + return self._input_force_mandatory - if len(self.input_force_mandatory) != self.number_inputs: - err_out_screen( - "Please specify InputMandatory values for each corresponding input " - "forcings in the configuration file." - ) - # Check to make sure enforcement options makes sense. - for enforce_opt in self.input_force_mandatory: - if enforce_opt < 0 or enforce_opt > 1: - err_out_screen( - "Invalid InputMandatory chosen in the configuration file. Please choose a value of 0 or 1 for each corresponding input forcing." - ) + @input_force_mandatory.setter + def input_force_mandatory(self, value: list) -> None: + """Specify whether the input forcings listed above are mandatory, or optional. This is important for layering contingencies if a product is missing, but forcing files are still desired. 0 - Not mandatory, 1 - Mandatory. NOTE!!! If no files are found for any products, code will error out indicating the final field is all missing values. - # Read in the output frequency - try: - self.output_freq = cfg_bmi["OutputFrequency"] - except ValueError as e: - err_out_screen( - "Improper OutputFrequency value specified in the configuration file." - ) - except KeyError as e: - err_out_screen( - "Unable to locate OutputFrequency in the configuration file." - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate OutputFrequency in the configuration file." - ) - if self.output_freq <= 0: - err_out_screen( - "Please specify an OutputFrequency that is greater than zero minutes." - ) + Example- InputMandatory: [1,1] + """ + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "InputMandatory") + self.check_input_values_in_range(value, "InputMandatory", [0, 1]) + self._input_force_mandatory = value - if self.precip_only_flag: - # Read in the custom supp output frequency - try: - self.customSuppPcpFreq = int(cfg_bmi["customSuppPcpFreq"]) - except ValueError as e: - err_out_screen( - "Improper customSuppPcpFreq value specified in the configuration file.", - e, - ) - except KeyError as e: - err_out_screen( - "Unable to locate customSuppPcpFreq in the configuration file.", e - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate customSuppPcpFreq in the configuration file.", e - ) - if self.output_freq <= 0: - err_out_screen( - "Please specify an customSuppPcpFreq that is greater than zero minutes." - ) + @property + def customSuppPcpFreq(self) -> int: + """Get the custom supplemental precip output frequency specified by the user in the configuration file. This is used to control the output frequency of supplemental precip forcings if the user has chosen to run the supplemental precip forcings module only.""" + return self._customSuppPcpFreq - # Read in the sub output hour - try: - self.sub_output_hour = int(cfg_bmi["SubOutputHour"]) - except ValueError as e: - err_out_screen( - "Improper SubOutputHour value specified in the configuration file.", e - ) - except KeyError as e: - err_out_screen( - "Unable to locate SubOutputHour in the configuration file.", e - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate SubOutputHour in the configuration file.", e - ) - if self.sub_output_hour < 0: - err_out_screen( - "Please specify an SubOutputHour that is greater than zero minutes." - ) - if self.sub_output_hour == 0: - self.sub_output_hour = None - # Read in the output frequency - try: - self.sub_output_freq = int(cfg_bmi["SubOutFreq"]) - except ValueError as e: - err_out_screen( - "Improper SubOutFreq value specified in the configuration file.", e - ) - except KeyError as e: - err_out_screen("Unable to locate SubOutFreq in the configuration file.", e) - except configparser.NoOptionError as e: - err_out_screen("Unable to locate SubOutFreq in the configuration file.", e) - if self.sub_output_freq < 0: - err_out_screen( - "Please specify an SubOutFreq that is greater than zero minutes." - ) - if self.sub_output_freq == 0: - self.sub_output_freq = None + @customSuppPcpFreq.setter + def customSuppPcpFreq(self, value: int) -> None: + """Set the custom supplemental precip output frequency specified by the user in the configuration file. This is used to control the output frequency of supplemental precip forcings if the user has chosen to run the supplemental precip forcings module only.""" + if self.precip_only_flag: + self.check_input_values_non_negative([value], "customSuppPcpFreq") + self._customSuppPcpFreq = value + else: + self._customSuppPcpFreq = None - # TODO Can this be a /tmp directory? - # Read in the scratch temporary directory, which also may contain output forcing file if requested. - try: - self.scratch_dir = cfg_bmi["ScratchDir"] - except ValueError as e: - err_out_screen( - "Improper ScratchDir specified in the configuration file.", e - ) - except KeyError as e: - err_out_screen("Unable to locate ScratchDir in the configuration file.", e) - except configparser.NoOptionError as e: - err_out_screen("Unable to locate ScratchDir in the configuration file.", e) + @property + def fcst_shift(self) -> int: + """Forecast cycles are determined by splitting up a day by equal ForecastFrequency interval. If there is a desire to shift the cycles to a different time step, ForecastShift will shift forecast cycles ahead by a determined set of minutes. For example, ForecastFrequency of 6 hours will produce forecasts cycles at 00, 06, 12, and 18 UTC. However, a ForecastShift of 1 hour will produce forecast cycles at 01, 07, 13, and 18 UTC. NOTE - This is only used by the realtime instance to calculate forecast cycles accordingly. Re-forecasts will use the beginning and ending dates specified in conjunction with the forecast frequency to determine forecast cycle dates. - self.make_scratch_dir() + Example- ForecastShift: 0 + """ + return self._fcst_shift - # Read in compression option - try: - self.useCompression = cfg_bmi["compressOutput"] - except KeyError as e: - err_out_screen("Unable to locate compressOut in the configuration file.", e) - except configparser.NoOptionError as e: - err_out_screen("Unable to locate compressOut in the configuration file.", e) - except ValueError as e: - err_out_screen("Improper compressOut value.", e) - if self.useCompression < 0 or self.useCompression > 1: - err_out_screen("Please choose a compressOut value of 0 or 1.") + @fcst_shift.setter + def fcst_shift(self, value: int) -> None: + if True: # was: self.realtime_flag: + self.check_input_values_non_negative([value], "ForecastShift") + # Calculate the beginning/ending processing dates if we are running realtime + self._fcst_shift = value + + # NOTE this commented out code copied from pre-refactored code on 5/6/2026 + # if self.refcst_flag: + # Calculate the number of forecasts to issue, and verify the user has chosen a + # correct divider based on the dates + # dt_tmp = self.e_date_proc - self.b_date_proc + # if (dt_tmp.days * 1440 + dt_tmp.seconds / 60.0) % self.fcst_freq != 0: + # err_out_screen('Please choose an equal divider forecast frequency for your ' + # 'specified reforecast range.') + # self.nFcsts = int((dt_tmp.days * 1440 + dt_tmp.seconds / 60.0) / self.fcst_freq) + + # Flag to constrain AORC forcing data cycle output + # for optTmp in self.input_forcings: + # if optTmp == 12: + # self.nFcsts = 1 - # Read in floating-point option - try: - self.useFloats = cfg_bmi["floatOutput"] - except KeyError as e: - # err_out_screen('Unable to locate floatOutput in the configuration file.', e) - self.useFloats = 0 - except configparser.NoOptionError as e: - # err_out_screen('Unable to locate floatOutput in the configuration file.', e) - self.useFloats = 0 - except ValueError as e: - err_out_screen( - "Improper floatOutput value: {}".format(cfg_bmi["includeLQFraq"]) - ) - if self.useFloats < 0 or self.useFloats > 1: - err_out_screen("Please choose a floatOutput value of 0 or 1.") + @property + def nFcsts(self): + """Get the number of forecasts to issue for a reforecast simulation based on the forecast shift and the processing window specified by the user in the configuration file. This is used to control how many forecast time steps are output for a reforecast simulation, and is only necessary if the user is running a reforecast simulation with a specified processing window rather than a realtime simulation.""" + return self._nFcsts - # Read in lqfrac option - try: - self.include_lqfrac = cfg_bmi["includeLQFrac"] - except KeyError as e: - # err_out_screen('Unable to locate includeLQFraq in the configuration file.', e) - self.include_lqfrac = 0 - except configparser.NoOptionError as e: - # err_out_screen('Unable to locate includeLQFraq in the configuration file.', e) - self.useFinclude_lqfracloats = 0 - except ValueError as e: - err_out_screen( - "Improper includeLQFrac value: {}".format(cfg_bmi["includeLQFraq"]), e - ) - if self.include_lqfrac < 0 or self.include_lqfrac > 1: - err_out_screen("Please choose an includeLQFrac value of 0 or 1.") + @nFcsts.setter + def nFcsts(self, value: int) -> None: + """Set the number of forecasts to issue for a reforecast simulation based on the forecast shift and the processing window specified by the user in the configuration file. This is used to control how many forecast time steps are output for a reforecast simulation, and is only necessary if the user is running a reforecast simulation with a specified processing window rather than a realtime simulation.""" + if value is None: + value = 1 + self._nFcsts = value - # Read in Forcing output option - try: - self.forcing_output = cfg_bmi["Output"] - except KeyError as e: - self.forcing_output = 0 - except configparser.NoOptionError as e: - self.forcing_output = 0 - except ValueError as e: - err_out_screen( - "Improper Forcing Output value: {}".format(cfg_bmi["Output"]), e - ) - if self.forcing_output < 0 or self.forcing_output > 1: - err_out_screen( - "Please choose a Forcing Output value of 0 (No output) or 1 (output)." - ) + @property + def fcst_input_horizons(self) -> list: + """Specify how much (in minutes) of each input forcing is desires for each forecast cycle. See documentation for examples. The length of this array must match the input forcing choices. - # Read AnA flag option - try: - # check both the Forecast section and if it's not there, the old BiasCorrection location - self.ana_flag = int(cfg_bmi["AnAFlag"]) - except KeyError as e: - err_out_screen("Unable to locate AnAFlag in the configuration file.", e) - except configparser.NoOptionError as e: - err_out_screen("Unable to locate AnAFlag in the configuration file.", e) - except ValueError as e: - err_out_screen("Improper AnAFlag value ", e) - if self.ana_flag < 0 or self.ana_flag > 1: - err_out_screen("Please choose a AnAFlag value of 0 or 1.") + - Example- ForecastInputHorizons: [60, 60] + """ + return self._fcst_input_horizons - # For the NextGen Forcings Engine BMI, we are assuming a realtime or reforecast simulation. - try: - self.look_back = cfg_bmi["LookBack"] - if self.look_back <= 0 and self.look_back != -9999: + @fcst_input_horizons.setter + def fcst_input_horizons(self, value: list) -> None: + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "ForecastInputHorizons") + self.check_input_values_non_negative(value, "ForecastInputHorizons") + else: + if len(self.fcst_input_horizons) != 1: err_out_screen( - "Please specify a positive LookBack or -9999 for realtime." + "Please specify ForecastInputHorizon values for each corresponding input forcings for forecasts." ) - except ValueError as e: - err_out_screen( - "Improper LookBack value entered into the configuration file. Please check your entry.", - e, - ) - except KeyError as e: - err_out_screen( - "Unable to locate LookBack in the configuration file. Please verify entries exist.", - e, - ) - except configparser.NoOptionError as e: + self._fcst_input_horizons = value + + @property + def fcst_input_offsets(self): + """Option for applying an offset to input forcings to use a different forecasted interval. For example, a user may wish to use 4-5 hour forecasted fields from an NWP grid from one of their input forcings. In that instance the offset would be 4 hours, but 0 for other remaining forcings. + + Example- ForecastInputOffsets: [0, 0] + """ + return self._fcst_input_offsets + + @fcst_input_offsets.setter + def fcst_input_offsets(self, value: list) -> None: + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "ForecastInputOffsets") + self.check_input_values_non_negative(value, "ForecastInputOffsets") + self._fcst_input_offsets = value + + @property + def cycle_length_minutes(self) -> int: + """Get the forecast cycle length in minutes, which is calculated based on the maximum of the forecast input horizons specified by the user in the configuration file. + + Ensure the number maximum cycle length is an equal divider of the output time step specified by the user. + """ + cycle_len = max(self.fcst_input_horizons) + if cycle_len % self.output_freq != 0: err_out_screen( - "Unable to locate LookBack in the configuration file. Please verify entries exist.", - e, + "Please specify an output time step that is an equal divider of the maximum of the forecast time horizons specified." ) + return cycle_len - # Process the beginning date of reforecast forcings to process - - if self.b_date_proc: - beg_date_tmp = self.b_date_proc - e = "" + @property + def num_output_steps(self) -> int: + """Calculate the number of output time steps per forecast cycle based on the forecast cycle length and the output frequency specified by the user in the configuration file.""" + if self.sub_output_hour is None: + num_steps = int(self.cycle_length_minutes / self.output_freq) else: - try: - beg_date_tmp = cfg_bmi["RefcstBDateProc"] - except KeyError as e: - err_out_screen( - "Unable to locate RefcstBDateProc under Logistics section in configuration file.", - e, - ) - beg_date_tmp = None - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate RefcstBDateProc under Logistics section in configuration file.", - e, + num_steps = ( + int( + (self.cycle_length_minutes - (self.sub_output_hour * 60)) + / self.sub_output_freq ) - beg_date_tmp = None + + int((self.sub_output_hour * 60) / self.output_freq) + - 1 + ) + return num_steps - if beg_date_tmp != -9999: - if isinstance(beg_date_tmp, str) and len(beg_date_tmp) != 12: - err_out_screen( - "Improper RefcstBDateProc length entered into the configuration file. Please check your entry.", - e, - ) - try: - self.b_date_proc = datetime.strptime(beg_date_tmp, "%Y%m%d%H%M") - except ValueError as e: - err_out_screen( - "Improper RefcstBDateProc value entered into the configuration file. Please check your entry.", - e, - ) + @property + def num_supp_output_steps(self) -> int: + """Calculate the number of supplemental precip output time steps per forecast cycle based on the forecast cycle length and the custom supplemental precip output frequency specified by the user in the configuration file.""" + if self.precip_only_flag: + return int(self.cycle_length_minutes / self.customSuppPcpFreq) + + @property + def actual_output_steps(self) -> int: + """Calculate the actual number of output time steps per forecast cycle based on whether the user has chosen to run a reforecast simulation with a specified processing window, which will only output time steps for which input forcings are available based on the processing window and forecast time horizons specified by the user in the configuration file.""" + if self.ana_flag: + return np.int32(self.nFcsts) else: - self.b_date_proc = -9999 + return np.int32(self.num_output_steps) - LOG.info(f"Begin date: {beg_date_tmp}") + @property + def grid_type(self) -> str: + """Tells the NextGen Forcings Engine BMI which grid type the engine is initalizing as a BMI instance. This is a required field and the proper string values should be "gridded", "hydrofabric", or "unstructured". - # If the Retro flag is off, and lookback is off, then we assume we are - # running a reforecast. - if self.look_back == -9999: - self.realtime_flag = False - self.refcst_flag = True - elif self.b_date_proc == -9999: - self.realtime_flag = True - self.refcst_flag = True - else: - # The processing window will be calculated based on current time and the - # lookback option since this is a realtime instance. - self.realtime_flag = False - self.refcst_flag = False - # self.b_date_proc = -9999 - # self.e_date_proc = -9999 + Example- GRID_TYPE: "gridded" + """ + return self._grid_type - # Calculate the delta time between the beginning and ending time of processing. - # self.process_window = self.e_date_proc - self.b_date_proc + @grid_type.setter + def grid_type(self, value: str) -> None: + """Set the grid type specified by the user in the configuration file. This is used to control how the program reads in and processes the geogrid information for regridding input forcings based on the grid type specified by the user in the configuration file.""" + self.check_input_values_in_range( + [value.lower()], "GRID_TYPE", ["gridded", "unstructured", "hydrofabric"] + ) + self._grid_type = value.lower() - # Read in the ForecastFrequency option. - try: - self.fcst_freq = cfg_bmi["ForecastFrequency"] - except ValueError as e: - err_out_screen( - "Improper ForecastFrequency value entered into the configuration file. Please check your entry.", - e, - ) - except KeyError as e: - err_out_screen( - "Unable to locate ForecastFrequency in the configuration file. Please verify entries exist.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate ForecastFrequency in the configuration file. Please verify entries exist.", - e, - ) - if self.fcst_freq <= 0: - err_out_screen( - "Please specify a ForecastFrequency in the configuration file greater than zero." - ) - # Currently, we only support daily or sub-daily forecasts. Any other iterations should - # be done using custom config files for each forecast cycle. - if self.fcst_freq > 1440: - err_out_screen( - "Only forecast cycles of daily or sub-daily are supported at this time" - ) + @property + def lon_var(self) -> str: + """Naming convention of the longitude variable within the "GeogridIn" file the user has specified. Variable naming convention ONLY for gridded domain configurations. This is required so the NextGen Forcings Engine BMI can dyanmically initialize the domain geogrid as an ESMF regridding object. In the case for "gridded" domain configuration options and a user specifying downscaling options while only specifying a height variable feature on the grid, this netcdf variable (LONVAR) is then EXPECTED to contain a netcdf metadata attribute called "dx" that specifies the grid spacing in the longtiudinal direction. Otherwise, it will throw an error and not be able to calculate the slope and tilt of each grid cell. - # Read in the ForecastShift option. This is ONLY done for the realtime instance as - # it's used to calculate the beginning of the processing window. - if True: # was: self.realtime_flag: - try: - self.fcst_shift = cfg_bmi["ForecastShift"] - except ValueError as e: - err_out_screen( - "Improper ForecastShift value entered into the configuration file. Please check your entry.", - e, - ) - except KeyError as e: - err_out_screen( - "Unable to locate ForecastShift in the configuration file. Please verify entries exist.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate ForecastShift in the configuration file. Please verify entries exist.", - e, - ) - if self.fcst_shift < 0: - err_out_screen( - "Please specify a ForecastShift in the configuration file greater than or equal to zero." - ) + Example- LONVAR: "XLONG_M" + """ + if self.grid_type == "gridded": + return self.extract_input_variable("LONVAR") - # Calculate the beginning/ending processing dates if we are running realtime - if self.realtime_flag: - calculate_lookback_window(self) - - # if self.refcst_flag: - # Calculate the number of forecasts to issue, and verify the user has chosen a - # correct divider based on the dates - # dt_tmp = self.e_date_proc - self.b_date_proc - # if (dt_tmp.days * 1440 + dt_tmp.seconds / 60.0) % self.fcst_freq != 0: - # err_out_screen('Please choose an equal divider forecast frequency for your ' - # 'specified reforecast range.') - # self.nFcsts = int((dt_tmp.days * 1440 + dt_tmp.seconds / 60.0) / self.fcst_freq) - - # Flag to constrain AORC forcing data cycle output - # for optTmp in self.input_forcings: - # if optTmp == 12: - # self.nFcsts = 1 - self.nFcsts = 1 + @property + def lat_var(self) -> str: + """Naming convention of the latitude variable within the "GeogridIn" file the user has specified. Variable naming convention ONLY for gridded domain configurations. This is required so the NextGen Forcings Engine BMI can dyanmically initialize the domain geogrid as an ESMF regridding object. In the case for "gridded" domain configuration options and a user specifying downscaling options while only specifying a height variable feature on the grid, this netcdf variable (LATVAR) is then EXPECTED to contain a netcdf metadata attribute called "dy" that specifies the grid spacing in the latitudinal direction. Otherwise, it will throw an error and not be able to calculate the slope and tilt of each grid cell. - if self.look_back != -9999: - calculate_lookback_window(self) + Example- LATVAR: "XLAT_M" + """ + if self.grid_type == "gridded": + return self.extract_input_variable("LATVAR") + + @property + def nodecoords_var(self) -> str: + """Naming convention of the node coordinates variable within the "GeogridIn" file the user has specified for ONLY an unstructured mesh or the NextGen hydrofabric. This is a 2-D array stating the latitude and longitude coordinates for all the nodes in the mesh. This is required so the NextGen Forcings Engine BMI can dyanmically initialize the domain geogrid as an ESMF regridding object. + + Example- NodeCoods: "nodecoords" + """ + if self.grid_type in ["unstructured", "hydrofabric"]: + return self.extract_input_variable("NodeCoords") + + @property + def elemcoords_var(self) -> str: + """Naming convention of the element coordinates variable within the "GeogridIn" file the user has specified for ONLY an unstructured mesh or the NextGen hydrofabric. This is a 2-D array stating the latitude and longitude coordinates for all the elements in the mesh. This is required so the NextGen Forcings Engine BMI can dyanmically initialize the domain geogrid as an ESMF regridding object. + + Example- ElemCoods: "elemcoords" + """ + if self.grid_type in ["unstructured", "hydrofabric"]: + return self.extract_input_variable("ElemCoords") + + @property + def elemconn_var(self) -> str: + """Naming convention of the element connectivity variable within the "GeogridIn" file the user has specified for ONLY an unstructured mesh or the NextGen hydrofabric. This is a 2-D array stating the node ids for each element connecting the entire mesh structure. This is required so the NextGen Forcings Engine BMI can dyanmically initialize the domain geogrid as an ESMF regridding object. + + Example- ElemConn: "elemconn" + """ + if self.grid_type in ["unstructured", "hydrofabric"]: + return self.extract_input_variable("ElemConn") + @property + def numelemconn_var(self) -> str: + """Naming convention of the number of nodes per element variable within the "GeogridIn" file the user has specified for ONLY an unstructured mesh or the NextGen hydrofabric. This is a 1-D array stating the how many nodes are connecting each element within the unstructured mesh. This is required so the NextGen Forcings Engine BMI can dyanmically initialize the domain geogrid as an ESMF regridding object. + + Example- NumElemConn: "numelemconn" + """ + if self.grid_type in ["unstructured", "hydrofabric"]: + return self.extract_input_variable("NumElemConn") + + @property + def element_id_var(self) -> str: + """Naming convention of the element id variable within the "GeogridIn" file the user has specified for ONLY the NextGen hydrofabric. This is a 1-D array stating the catchment id numeric naming convention within the "divides" geopackage layer of a given NextGen hydrofabric file. This variable is required in order for the NextGen Forcings Engine to properly advertise the element ids of the unstructured mesh linked to the NextGen hydrofabric catchment ids. + + Example- ElemID: "element_ids" + """ + if self.grid_type == "hydrofabric": + return self.extract_input_variable("ElemID") + + @property + def ignored_border_widths(self) -> list: + """Border width (in grid cells) to ignore for each input dataset. NOTE: generally, the first input forcing should always be zero or there will be missing data in the final output. + + Example- IgnoredBorderWidths: [0,10] + """ + return self._ignored_border_widths + + @ignored_border_widths.setter + def ignored_border_widths(self, value: list) -> None: + """Set the list of ignored border widths specified by the user in the configuration file. This is used to control how the program processes input forcings based on the ignored border widths specified for each input forcing in the configuration file.""" if not self.precip_only_flag: - # Read in the ForecastInputHorizons options. - try: - self.fcst_input_horizons = cfg_bmi["ForecastInputHorizons"] - except KeyError as e: - err_out_screen( - "Unable to locate ForecastInputHorizons under Forecast section in configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate ForecastInputHorizons under Forecast section in configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper ForecastInputHorizons option specified in configuration file", - e, - ) - if len(self.fcst_input_horizons) != self.number_inputs: - err_out_screen( - "Please specify ForecastInputHorizon values for each corresponding input forcings for forecasts." - ) + self.check_number_of_inputs_forcings(value, "IgnoredBorderWidths") + self.check_input_values_non_negative(value, "IgnoredBorderWidths") + self._ignored_border_widths = value - # Check to make sure the horizons options make sense. There will be additional - # checking later when input choices are mapped to input products. - for horizonOpt in self.fcst_input_horizons: - if horizonOpt <= 0: - err_out_screen( - "Please specify ForecastInputHorizon values greater than zero." - ) + @property + def regrid_opt(self): + """Choose regridding options for each input forcing files being used. Options available are: 1 - ESMF Bilinear, 2 - ESMF Nearest Neighbor, 3 - ESMF Conservative Bilinear. + + Example- RegridOpt: [1,1] + """ + return self._regrid_opt + + @regrid_opt.setter + def regrid_opt(self, value: list) -> None: + """Set the list of regridding options specified by the user in the configuration file. This is used to control how input forcings are regridded based on the regridding option specified for each input forcing in the configuration file.""" + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "RegridOpt") + self.check_input_values_in_range(value, "RegridOpt", [1, 2, 3]) + self._regrid_opt = value else: - # Read in the ForecastInputHorizons options. - try: - self.fcst_input_horizons = cfg_bmi["ForecastInputHorizons"] - except KeyError as e: - err_out_screen( - "Unable to locate ForecastInputHorizons under Forecast section in configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate ForecastInputHorizons under Forecast section in configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper ForecastInputHorizons option specified in configuration file", - e, - ) - if len(self.fcst_input_horizons) != 1: - err_out_screen( - "Please specify ForecastInputHorizon values for each corresponding input forcings for forecasts." - ) + self._regrid_opt = None + @property + def weightsDir(self) -> str: + """Get the pathway to the ESMF weights directory specified by the user in the configuration file. This is used to control where the program looks for ESMF weights files if the user has chosen to use pre-generated ESMF weights files for regridding input forcings in the configuration file.""" + return self._weightsDir + + @weightsDir.setter + def weightsDir(self, value: str) -> None: + """Set the pathway to the ESMF weights directory specified by the user in the configuration file. This is used to control where the program looks for ESMF weights files if the user has chosen to use pre-generated ESMF weights files for regridding input forcings in the configuration file.""" if not self.precip_only_flag: - # Read in the ForecastInputOffsets options. - try: - self.fcst_input_offsets = cfg_bmi["ForecastInputOffsets"] - except KeyError as e: - err_out_screen( - "Unable to locate ForecastInputOffsets under Forecast section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate ForecastInputOffsets under Forecast section in the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper ForecastInputOffsets option specified in the configuration file.", - e, - ) - if len(self.fcst_input_offsets) != self.number_inputs: + if value is not None and not os.path.exists(value): err_out_screen( - "Please specify ForecastInputOffset values for each corresponding input forcings for forecasts." + f"ESMF Weights file directory specified ({value}) but does not exist" ) - # Check to make sure the input offset options make sense. There will be additional - # checking later when input choices are mapped to input products. - for inputOffset in self.fcst_input_offsets: - if inputOffset < 0: - err_out_screen( - "Please specify ForecastInputOffset values greater than or equal to zero." - ) + self._weightsDir = value - # Calculate the length of the forecast cycle, based on the maximum - # length of the input forcing length chosen by the user. - self.cycle_length_minutes = max(self.fcst_input_horizons) + @property + def forceTemoralInterp(self) -> list: + """Get the list of forcing temporal interpolation options specified by the user in the configuration file. This is used to control how input forcings are temporally interpolated based on the temporal interpolation option specified for each input forcing in the configuration file.""" + return self._forceTemoralInterp - # Ensure the number maximum cycle length is an equal divider of the output - # time step specified by the user. - if self.cycle_length_minutes % self.output_freq != 0: - err_out_screen( - "Please specify an output time step that is an equal divider of the maximum of the forecast time horizons specified." + @forceTemoralInterp.setter + def forceTemoralInterp(self, value: list) -> None: + """Specify an temporal interpolation for the forcing variables. Interpolation will be done between the two neighboring input forcing states that exist. If only one nearest state exist (I.E. only a state forward in time, or behind), then that state will be used as a "nearest neighbor". NOTE - All input options here must be of the same length of the input forcing number. Also note all temporal interpolation occurs BEFORE downscaling and bias correction. 0 - No temporal interpolation. 1 - Nearest Neighbor, 2 - Linear weighted, average. + + Example- ForcingTemporalInterpolation: [0,0] + """ + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "ForcingTemporalInterpolation") + self.check_input_values_in_range( + value, "ForcingTemporalInterpolation", [0, 1, 2] ) + self._forceTemoralInterp = value - if self.sub_output_hour is None: - # Calculate the number of output time steps per forecast cycle. - self.num_output_steps = int(self.cycle_length_minutes / self.output_freq) - if self.precip_only_flag: - self.num_supp_output_steps = ( - int(self.cycle_length_minutes) / self.customSuppPcpFreq - ) - if self.ana_flag: - self.actual_output_steps = np.int32(self.nFcsts) - else: - self.actual_output_steps = np.int32(self.num_output_steps) - else: - # Calculate the number of output time steps per forecast cycle. - self.num_output_steps = ( - int( - (self.cycle_length_minutes - (self.sub_output_hour * 60)) - / self.sub_output_freq - ) - + int((self.sub_output_hour * 60) / self.output_freq) - - 1 - ) - if self.precip_only_flag: - self.num_supp_output_steps = ( - int(self.cycle_length_minutes) / self.customSuppPcpFreq - ) - if self.ana_flag: - self.actual_output_steps = np.int32(self.nFcsts) - else: - self.actual_output_steps = np.int32(self.num_output_steps) + @property + def t2dDownscaleOpt(self) -> list: + """Specify a temperature downscaling method: 0 - No downscaling, 1 - Use a simple lapse rate of 6.75 degrees Celsius to get from the model elevation to the WRF-Hydro elevation, 2 - Use a pre-calculated lapse rate regridded to the WRF-Hydro domain (only NWM), 3 - Use a dynamic lapse rate calculated at each timstep. - # Process the grid type - try: - self.grid_type = cfg_bmi["GRID_TYPE"] - except KeyError as e: - err_out_screen("Unable to locate GRID_TYPE in the configuration file.", e) - except configparser.NoOptionError as e: - err_out_screen("Unable to locate GRID_TYPE in the configuration file.", e) - if ( - self.grid_type.lower() != "gridded" - and self.grid_type.lower() != "unstructured" - and self.grid_type.lower() != "hydrofabric" - ): - err_out_screen( - 'GRID_TYPE in the configuration file only accepts "unstructured", "gridded", or "hydrofabric" as options.' - ) + Example- TemperatureDownscaling: [3, 3] + """ + return self._t2dDownscaleOpt - if self.grid_type.lower() == "gridded": - # Process the geogrid variable information - try: - self.lon_var = cfg_bmi["LONVAR"] - except KeyError as e: - err_out_screen("Unable to locate LONVAR in the configuration file.", e) - except configparser.NoOptionError as e: - err_out_screen("Unable to locate LONVAR in the configuration file.", e) - try: - self.lat_var = cfg_bmi["LATVAR"] - except KeyError as e: - err_out_screen("Unable to locate LATVAR in the configuration file.", e) - except configparser.NoOptionError as e: - err_out_screen("Unable to locate LATVAR in the configuration file.", e) - - elif self.grid_type.lower() == "unstructured": - # Process the geogrid variable information - try: - self.nodecoords_var = cfg_bmi["NodeCoords"] - except KeyError as e: - err_out_screen( - "Unable to locate NodeCoords for unstructured mesh in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate NodeCoords for unstructured mesh in the configuration file.", - e, - ) - try: - self.elemcoords_var = cfg_bmi["ElemCoords"] - except KeyError as e: - err_out_screen( - "Unable to locate ElemCoords for unstructured mesh in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate ElemCoords for unstructured mesh in the configuration file.", - e, - ) - try: - self.elemconn_var = cfg_bmi["ElemConn"] - except KeyError as e: - err_out_screen( - "Unable to locate ElemConn for unstructured mesh in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate ElemConn for unstructured mesh in the configuration file.", - e, - ) - try: - self.numelemconn_var = cfg_bmi["NumElemConn"] - except KeyError as e: - err_out_screen( - "Unable to locate NumElemConn for unstructured mesh in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate NumElemConn for unstructured mesh in the configuration file.", - e, - ) + @t2dDownscaleOpt.setter + def t2dDownscaleOpt(self, value: list) -> None: + """Set the list of temperature downscaling options specified by the user in the configuration file. This is used to control how temperature input forcings are downscaled based on the temperature downscaling option specified for each input forcing in the configuration file.""" + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "TemperatureDownscaling") + self.check_input_values_in_range(value, "TemperatureDownscaling", [0, 1, 2]) + count = 0 + for opt in value: + if opt == 2: + self.param_flag[count] = 1 + count += 1 + self._t2dDownscaleOpt = value - elif self.grid_type.lower() == "hydrofabric": - # Process the geogrid variable information - try: - self.nodecoords_var = cfg_bmi["NodeCoords"] - except KeyError as e: - err_out_screen( - "Unable to locate NodeCoords for unstructured mesh in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate NodeCoords for unstructured mesh in the configuration file.", - e, - ) - try: - self.elemcoords_var = cfg_bmi["ElemCoords"] - except KeyError as e: - err_out_screen( - "Unable to locate ElemCoords for unstructured mesh in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate ElemCoords for unstructured mesh in the configuration file.", - e, - ) - try: - self.element_id_var = cfg_bmi["ElemID"] - except KeyError as e: - err_out_screen( - "Unable to locate ElemID for unstructured mesh in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate ElemID for unstructured mesh in the configuration file.", - e, - ) - try: - self.elemconn_var = cfg_bmi["ElemConn"] - except KeyError as e: - err_out_screen( - "Unable to locate ElemConn for unstructured mesh in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate ElemConn for unstructured mesh in the configuration file.", - e, - ) - try: - self.numelemconn_var = cfg_bmi["NumElemConn"] - except KeyError as e: - err_out_screen( - "Unable to locate NumElemConn for unstructured mesh in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate NumElemConn for unstructured mesh in the configuration file.", - e, - ) + @property + def psfcDownscaleOpt(self) -> list: + """Specify a surface pressure downscaling method: 0 - No downscaling, 1 - Use input elevation and WRF-Hydro elevation to downscale surface pressure. - # Process geospatial information + Example- PressureDownscaling: [1, 1] + """ + return self._psfcDownscaleOpt - if self.geogrid: - LOG.debug(f"Geogrid: {self.geogrid}") - else: - try: - self.geogrid = cfg_bmi["GeogridIn"] - except KeyError as e: - err_out_screen( - "Unable to locate GeogridIn in the configuration file.", e - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate GeogridIn in the configuration file.", e - ) + @psfcDownscaleOpt.setter + def psfcDownscaleOpt(self, value: list) -> None: + """Set the list of pressure downscaling options specified by the user in the configuration file. This is used to control how pressure input forcings are downscaled based on the pressure downscaling option specified for each input forcing in the configuration file.""" + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "PressureDownscaling") + self.check_input_values_in_range(value, "PressureDownscaling", [0, 1]) + self._psfcDownscaleOpt = value - # Check for the optional geospatial land metadata file. - try: - self.spatial_meta = cfg_bmi["SpatialMetaIn"] - except KeyError as e: - err_out_screen( - "Unable to locate SpatialMetaIn in the configuration file.", e - ) - if len(self.spatial_meta) == 0: - # No spatial metadata file found. - self.spatial_meta = None - else: - if not os.path.isfile(self.spatial_meta): - err_out_screen( - "Unable to locate optional spatial metadata file: " - + self.spatial_meta - ) + @property + def swDownscaleOpt(self) -> list: + """Specify a shortwave radiation downscaling routine. 0 - No downscaling, 1 - Run a topographic adjustment using the WRF-Hydro elevation. + + Example- ShortwaveDownscaling: [1, 1] + """ + return self._swDownscaleOpt + @swDownscaleOpt.setter + def swDownscaleOpt(self, value: list) -> None: + """Set the list of shortwave downscaling options specified by the user in the configuration file. This is used to control how shortwave radiation input forcings are downscaled based on the shortwave downscaling option specified for each input forcing in the configuration file.""" if not self.precip_only_flag: - # Check for the IgnoredBorderWidths - try: - self.ignored_border_widths = cfg_bmi["IgnoredBorderWidths"] - except (KeyError, configparser.NoOptionError): - # if didn't specify, no worries, just set to 0 - self.ignored_border_widths = [0.0] * self.number_inputs - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper IgnoredBorderWidths option specified in the configuration file." - "({} was supplied".format( - cfg_bmi["Geospatial"]["IgnoredBorderWidths"] - ), - e, - ) - if len(self.ignored_border_widths) != self.number_inputs: - err_out_screen( - "Please specify IgnoredBorderWidths values for each " - "corresponding input forcings for SuppForcing." - "({} was supplied".format(self.ignored_border_widths) - ) - if any(map(lambda x: x < 0, self.ignored_border_widths)): - err_out_screen( - "Please specify IgnoredBorderWidths values greater than or equal to zero:" - "({} was supplied".format(self.ignored_border_widths) - ) + self.check_number_of_inputs_forcings(value, "ShortwaveDownscaling") + self.check_input_values_in_range(value, "ShortwaveDownscaling", [0, 1]) + self._swDownscaleOpt = value + + @property + def q2dDownscaleOpt(self) -> list: + """Specify a specific humidity downscaling routine. 0 - No downscaling, 1 - Use regridded humidity, along with downscaled temperature/pressure to extrapolate a downscaled surface specific humidty. + + Example- HumidityDownscaling: [1, 1] + """ + return self._q2dDownscaleOpt + @q2dDownscaleOpt.setter + def q2dDownscaleOpt(self, value: list) -> None: + """Set the list of humidity downscaling options specified by the user in the configuration file. This is used to control how humidity input forcings are downscaled based on the humidity downscaling option specified for each input forcing in the configuration file.""" if not self.precip_only_flag: - # Process regridding options. - try: - self.regrid_opt = cfg_bmi["RegridOpt"] - except KeyError as e: - err_out_screen( - "Unable to locate RegridOpt under the Regridding section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate RegridOpt under the Regridding section in the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper RegridOpt options specified in the configuration file.", e - ) - if len(self.regrid_opt) != self.number_inputs: - err_out_screen( - "Please specify RegridOpt values for each corresponding input forcings in the configuration file.", - e, - ) - # Check to make sure regridding options makes sense. - for regridOpt in self.regrid_opt: - if regridOpt < 1 or regridOpt > 3: - err_out_screen( - "Invalid RegridOpt chosen in the configuration file. Please choose a " - "value of 1-2 for each corresponding input forcing." - ) - try: - # Read weight file directory (optional) - self.weightsDir = cfg_bmi["RegridWeightsDir"] - except Exception: - # Set wieghtsDir to None; this will create regrid object in memory - self.weightsDir = None - if self.weightsDir: - # if we do have one specified, make sure it exists - if not os.path.exists(self.weightsDir): - err_out_screen( - "ESMF Weights file directory specified ({}) but does not exist" - ).format(self.weightsDir) + self.check_number_of_inputs_forcings(value, "HumidityDownscaling") + self.check_input_values_in_range(value, "HumidityDownscaling", [0, 1]) + self._q2dDownscaleOpt = value - # Calculate the beginning/ending processing dates if we are running realtime - if self.realtime_flag: - calculate_lookback_window(self) + @property + def precipDownscaleOpt(self) -> list: + """Specify a precipitation downscaling routine. 0 - No downscaling, 1 - NWM mountain mapper downscaling using monthly PRISM climo. - # Create temporary array to hold flags if we need input parameter files. - param_flag = np.empty([len(self.input_forcings)], int) - param_flag[:] = 0 + Example- PrecipDownscaling: [0, 0] + """ + return self._precipDownscaleOpt + + @precipDownscaleOpt.setter + def precipDownscaleOpt(self, value: list) -> None: + """Set the list of precipitation downscaling options specified by the user in the configuration file. This is used to control how precipitation input forcings are downscaled based on the precipitation downscaling option specified for each input forcing in the configuration file.""" if not self.precip_only_flag: - # Read in temporal interpolation options. - try: - self.forceTemoralInterp = cfg_bmi["ForcingTemporalInterpolation"] - except KeyError as e: - err_out_screen( - "Unable to locate ForcingTemporalInterpolation under the Interpolation section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate ForcingTemporalInterpolation under the Interpolation section in the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper ForcingTemporalInterpolation options specified in the configuration file.", - e, - ) - if len(self.forceTemoralInterp) != self.number_inputs: - err_out_screen( - "Please specify ForcingTemporalInterpolation values for each corresponding input forcings in the configuration file." - ) - # Ensure the forcingTemporalInterpolation values make sense. - for temporalInterpOpt in self.forceTemoralInterp: - if temporalInterpOpt < 0 or temporalInterpOpt > 2: - err_out_screen( - "Invalid ForcingTemporalInterpolation chosen in the configuration file. " - "Please choose a value of 0-2 for each corresponding input forcing." - ) + self.check_number_of_inputs_forcings(value, "PrecipDownscaling") + self.check_input_values_in_range(value, "PrecipDownscaling", [0, 1]) + count = 0 + for opt in value: + if opt == 1: + self.param_flag[count] = 1 + count += 1 + self._precipDownscaleOpt = value - # Read in the temperature downscaling options. - try: - self.t2dDownscaleOpt = cfg_bmi["TemperatureDownscaling"] - except KeyError as e: - err_out_screen( - "Unable to locate TemperatureDownscaling under the Downscaling section of the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate TemperatureDownscaling under the Downscaling section of the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper TemperatureDownscaling options specified in the configuration file.", - e, - ) - if len(self.t2dDownscaleOpt) != self.number_inputs: - err_out_screen( - "Please specify TemperatureDownscaling values for each corresponding input forcings in the configuration file." - ) - # Ensure the downscaling options chosen make sense. - count_tmp = 0 - for optTmp in self.t2dDownscaleOpt: - if optTmp < 0 or optTmp > 2: - err_out_screen( - "Invalid TemperatureDownscaling options specified in the configuration file." - ) - if optTmp == 2: - param_flag[count_tmp] = 1 - count_tmp = count_tmp + 1 + @property + def dScaleParamDirs(self) -> list: + """Specify the input parameter directory containing necessary downscaling grids. This is ONLY needed for the original NWM WRF-Hydro domain. Otherwise, just point it to a random directory and it will be ignored. - # Read in the pressure downscaling options. - try: - self.psfcDownscaleOpt = cfg_bmi["PressureDownscaling"] - except KeyError as e: - err_out_screen( - "Unable to locate PressureDownscaling under the Downscaling section of the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate PressureDownscaling under the Downscaling section of the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper PressureDownscaling options specified in the configuration file." - ) - if len(self.psfcDownscaleOpt) != self.number_inputs: - err_out_screen( - "Please specify PressureDownscaling values for each corresponding input forcings in the configuration file." - ) - # Ensure the downscaling options chosen make sense. - for optTmp in self.psfcDownscaleOpt: - if optTmp < 0 or optTmp > 1: - err_out_screen( - "Invalid PressureDownscaling options specified in the configuration file." - ) + Example- DownscalingParamDirs: ["./forcingParam/AnA", "./forcingParam/AnA"] + """ + return self._dScaleParamDirs - # Read in the shortwave downscaling options - try: - self.swDownscaleOpt = cfg_bmi["ShortwaveDownscaling"] - except KeyError as e: - err_out_screen( - "Unable to locate ShortwaveDownscaling under the Downscaling section of the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate ShortwaveDownscaling under the Downscaling section of the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper ShortwaveDownscaling options specified in the configuration file.", - e, - ) - if len(self.swDownscaleOpt) != self.number_inputs: + @dScaleParamDirs.setter + def dScaleParamDirs(self, value: list) -> None: + """Set the list of downscaling parameter directories specified by the user in the configuration file. This is used to control where the program looks for downscaling parameter files for each input forcing based on the downscaling parameter directory specified for each input forcing in the configuration file.""" + self.check_number_of_inputs_forcings(value, "DownscalingParamDirs") + for dirTmp in range(0, len(value)): + dir_path = value[dirTmp] + if not os.path.isdir(dir_path): err_out_screen( - "Please specify ShortwaveDownscaling values for each corresponding input forcings in the configuration file." + f"Unable to locate parameter directory: {os.path.abspath(dir_path)}" ) - # Ensure the downscaling options chosen make sense. - for optTmp in self.swDownscaleOpt: - if optTmp < 0 or optTmp > 1: - err_out_screen( - "Invalid ShortwaveDownscaling options specified in the configuration file." - ) + self._dScaleParamDirs = value - # Read in humidity downscaling options. - try: - self.q2dDownscaleOpt = cfg_bmi["HumidityDownscaling"] - except KeyError as e: - err_out_screen( - "Unable to locate HumidityDownscaling under the Downscaling section of the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate HumidityDownscaling under the Downscaling section of the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper HumidityDownscaling options specified in the configuration file.", - e, - ) - if len(self.q2dDownscaleOpt) != self.number_inputs: - err_out_screen( - "Please specify HumidityDownscaling values for each corresponding " - "input forcings in the configuration file." - ) - # Ensure the downscaling options chosen make sense. - for optTmp in self.q2dDownscaleOpt: - if optTmp < 0 or optTmp > 1: - err_out_screen( - "Invalid HumidityDownscaling options specified in the configuration file." - ) + @property + def perform_downscaling(self) -> bool: + """Determine whether downscaling of input forcings is necessary based on the downscaling options specified by the user for each input forcing in the configuration file.""" + if ( + 1 in self.q2dDownscaleOpt + or 1 in self.swDownscaleOpt + or 1 in self.psfcDownscaleOpt + or 1 in self.t2dDownscaleOpt + or 2 in self.t2dDownscaleOpt + ): + return True + else: + return False - # Read in the precipitation downscaling options - try: - self.precipDownscaleOpt = cfg_bmi["PrecipDownscaling"] - except KeyError as e: - err_out_screen( - "Unable to locate PrecipDownscaling under the Downscaling section of the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate PrecipDownscaling under the Downscaling section of the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper PrecipDownscaling options specified in the configuration file.", - e, + @property + def t2BiasCorrectOpt(self) -> list: + """Specify a temperature bias correction method. 0 - No bias correction, 1 - CFSv2 - NLDAS2 Parametric Distribution - NWM ONLY, 2 - Custom NCAR bias-correction based on HRRRv3 analysis - based on hour of day (USE WITH CAUTION), 3 - NCAR parametric GFS bias correction, 4 - NCAR parametric HRRR bias correction. + + Example- TemperatureBiasCorrection: [0, 4] + """ + return self._t2BiasCorrectOpt + + @t2BiasCorrectOpt.setter + def t2BiasCorrectOpt(self, value: list) -> None: + """Set the list of temperature bias correction options specified by the user in the configuration file. This is used to control how temperature input forcings are bias corrected based on the temperature bias correction option specified for each input forcing in the configuration file.""" + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "TemperatureBiasCorrection") + self.check_input_values_in_range( + value, "TemperatureBiasCorrection", [0, 1, 2, 3, 4] ) + self._t2BiasCorrectOpt = value + + @property + def psfcBiasCorrectOpt(self) -> list: + """Specify a surface pressure bias correction method. 0 - No bias correction, 1 - CFSv2 - NLDAS2 Parametric Distribution - NWM ONLY. + + Example- PressureBiasCorrection: [0,0] + """ + return self._psfcBiasCorrectOpt + + @psfcBiasCorrectOpt.setter + def psfcBiasCorrectOpt(self, value: list) -> None: + """Set the list of pressure bias correction options specified by the user in the configuration file. This is used to control how pressure input forcings are bias corrected based on the pressure bias correction option specified for each input forcing in the configuration file.""" if not self.precip_only_flag: - if len(self.precipDownscaleOpt) != self.number_inputs: - err_out_screen( - "Please specify PrecipDownscaling values for each corresponding " - "input forcings in the configuration file." - ) - # Ensure the downscaling options chosen make sense. - count_tmp = 0 - for optTmp in self.precipDownscaleOpt: - if optTmp < 0 or optTmp > 1: - err_out_screen( - "Invalid PrecipDownscaling options specified in the configuration file." - ) - if optTmp == 1: - param_flag[count_tmp] = 1 - count_tmp = count_tmp + 1 + self.check_number_of_inputs_forcings(value, "PressureBiasCorrection") + self.check_input_values_in_range(value, "PressureBiasCorrection", [0, 1]) + self._psfcBiasCorrectOpt = value - # Read in the downscaling parameter directory. - try: - self.dScaleParamDirs = cfg_bmi["DownscalingParamDirs"] - except KeyError as e: - err_out_screen( - "Unable to locate DownscalingParamDirs in the configuration file.", e - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate DownscalingParamDirs in the configuration file.", e - ) - if len(self.dScaleParamDirs) != len(self.input_forcings): - err_out_screen( - "Please specify a downscaling parameter directory for each " - "corresponding downscaling option that requires one." - ) - # Loop through each downscaling parameter directory and make sure they exist. - for dirTmp in range(0, len(self.dScaleParamDirs)): - if not os.path.isdir(self.dScaleParamDirs[dirTmp]): - err_out_screen( - "Unable to locate parameter directory: " - + os.path.abspath(self.dScaleParamDirs[dirTmp]) - ) + @property + def q2BiasCorrectOpt(self): + """Specify a specific humidity bias correction method. 0 - No bias correction, 1 - CFSv2 - NLDAS2 Parametric Distribution - NWM ONLY, 2 - Custom NCAR bias-correction based on HRRRv3 analysis - based on hour of day (USE WITH CAUTION). - if ( - [1] in self.q2dDownscaleOpt - or [1] in self.swDownscaleOpt - or [1] in self.psfcDownscaleOpt - or [1, 2] in self.t2dDownscaleOpt - ): - # Process the geogrid information for downscaling - try: - self.sinalpha_var = cfg_bmi["SINALPHA"] - except Exception: - self.sinalpha_var = None - try: - self.cosalpha_var = cfg_bmi["COSALPHA"] - except Exception: - self.cosalpha_var = None - if self.grid_type.lower() == "hydrofabric": - try: - self.slope_var = cfg_bmi["SLOPE"] - except KeyError as e: - err_out_screen( - "Unable to locate SLOPE variable in the hydrofabric configuration file. Required variable since user turned on a downscaling option.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate SLOPE variable in the hydrofabric configuration file. Required variable since user turned on a downscaling option.", - e, - ) - try: - self.slope_azimuth_var = cfg_bmi["SLOPE_AZIMUTH"] - except KeyError as e: - err_out_screen( - "Unable to locate SLOPE_AZIMUTH variable in the hydrofabric configuration file. Required variable since user turned on a downscaling option.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate SLOPE_AZIMUTH variable in the hydrofabric configuration file. Required variable since user turned on a downscaling option.", - e, - ) - else: - try: - self.slope_var = cfg_bmi["SLOPE"] - except Exception: - self.slope_var = None - try: - self.slope_azimuth_var = cfg_bmi["SLOPE_AZIMUTH"] - except Exception: - self.slope_azimuth_var = None - if self.grid_type.lower() == "unstructured": - try: - self.slope_var_elem = cfg_bmi["SLOPE_ELEM"] - except Exception: - self.slope_var_elem = None - try: - self.slope_azimuth_var_elem = cfg_bmi["SLOPE_AZIMUTH_ELEM"] - except Exception: - self.slope_azimuth_var_elem = None - - if self.grid_type.lower() == "unstructured": - try: - self.hgt_elem_var = cfg_bmi["HGTVAR_ELEM"] - except KeyError as e: - err_out_screen( - "Unable to locate HGTVAR_ELEM in the configuration file. Required variable since user turned on a downscaling option.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate HGTVAR_ELEM in the configuration file. Required variable since user turned on a downscaling option.", - e, - ) + Example- HumidityBiasCorrection: [0,0] + """ + return self._q2BiasCorrectOpt - try: - self.hgt_var = cfg_bmi["HGTVAR"] - except KeyError as e: - err_out_screen( - "Unable to locate HGTVAR in the configuration file. Required variable since user turned on a downscaling option.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate HGTVAR in the configuration file. Required variable since user turned on a downscaling option.", - e, - ) + @q2BiasCorrectOpt.setter + def q2BiasCorrectOpt(self, value): + """Set the list of humidity bias correction options specified by the user in the configuration file. This is used to control how humidity input forcings are bias corrected based on the humidity bias correction option specified for each input forcing in the configuration file.""" + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "HumidityBiasCorrection") + self.check_input_values_in_range(value, "HumidityBiasCorrection", [0, 1, 2]) + self._q2BiasCorrectOpt = value - # * Bias Correction Options * + @property + def windBiasCorrect(self): + """Specify a wind bias correction. 0 - No bias correction, 1 - CFSv2 - NLDAS2 Parametric Distribution - NWM ONLY, 2 - Custom NCAR bias-correction based on HRRRv3 analysis - based on hour of day (USE WITH CAUTION), 3 - NCAR parametric GFS bias correction, 4 - NCAR parametric HRRR bias correction. + + Example- WindBiasCorrection: [0, 4] + """ + return self._windBiasCorrect + + @windBiasCorrect.setter + def windBiasCorrect(self, value): + """Set the list of wind bias correction options specified by the user in the configuration file. This is used to control how wind input forcings are bias corrected based on the wind bias correction option specified for each input forcing in the configuration file.""" if not self.precip_only_flag: - # Read in temperature bias correction options - try: - self.t2BiasCorrectOpt = cfg_bmi["TemperatureBiasCorrection"] - except KeyError as e: - err_out_screen( - "Unable to locate TemperatureBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate TemperatureBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except json.JSONDecodeError as e: - err_out_screen( - "Improper TemperatureBiasCorrection options specified in the configuration file.", - e, - ) - if len(self.t2BiasCorrectOpt) != self.number_inputs: - err_out_screen( - "Please specify TemperatureBiasCorrection values for each corresponding input forcings in the configuration file." - ) - # Ensure the bias correction options chosen make sense. - for optTmp in self.t2BiasCorrectOpt: - if optTmp < 0 or optTmp > 4: - err_out_screen( - "Invalid TemperatureBiasCorrection options specified in the configuration file." - ) + self.check_number_of_inputs_forcings(value, "WindBiasCorrection") + self.check_input_values_in_range( + value, "WindBiasCorrection", [0, 1, 2, 3, 4] + ) + self._windBiasCorrect = value - # Read in surface pressure bias correction options. - try: - self.psfcBiasCorrectOpt = cfg_bmi["PressureBiasCorrection"] - except KeyError as e: - err_out_screen( - "Unable to locate PressureBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate PressureBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except json.JSONDecodeError as e: - err_out_screen( - "Improper PressureBiasCorrection options specified in the configuration file.", - e, - ) - if len(self.psfcDownscaleOpt) != self.number_inputs: - err_out_screen( - "Please specify PressureBiasCorrection values for each corresponding input forcings in the configuration file." - ) - # Ensure the bias correction options chosen make sense. - for optTmp in self.psfcBiasCorrectOpt: - if optTmp < 0 or optTmp > 1: - err_out_screen( - "Invalid PressureBiasCorrection options specified in the configuration file." - ) - if optTmp == 1: - # We are running NWM-Specific bias-correction of CFSv2 that needs to take place prior to regridding. - self.runCfsNldasBiasCorrect = True + @property + def swBiasCorrectOpt(self) -> list: + """Specify a bias correction for incoming short wave radiation flux. 0 - No bias correction, 1 - CFSv2 - NLDAS2 Parametric Distribution - NWM ONLY, 2 - Custom NCAR bias-correction based on HRRRv3 analysis (USE WITH CAUTION). - # Read in humidity bias correction options. - try: - self.q2BiasCorrectOpt = cfg_bmi["HumidityBiasCorrection"] - except KeyError as e: - err_out_screen( - "Unable to locate HumidityBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate HumidityBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except json.JSONDecodeError as e: - err_out_screen( - "Improper HumdityBiasCorrection options specified in the configuration file.", - e, - ) - if len(self.q2BiasCorrectOpt) != self.number_inputs: - err_out_screen( - "Please specify HumidityBiasCorrection values for each corresponding input forcings in the configuration file." - ) - # Ensure the bias correction options chosen make sense. - for optTmp in self.q2BiasCorrectOpt: - if optTmp < 0 or optTmp > 2: - err_out_screen( - "Invalid HumidityBiasCorrection options specified in the configuration file." - ) - if optTmp == 1: - # We are running NWM-Specific bias-correction of CFSv2 that needs to take place prior to regridding. - self.runCfsNldasBiasCorrect = True + Example- SwBiasCorrection: [0, 2] + """ + return self._swBiasCorrectOpt - # Read in wind bias correction options. - try: - self.windBiasCorrect = cfg_bmi["WindBiasCorrection"] - except KeyError as e: - err_out_screen( - "Unable to locate WindBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate WindBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except json.JSONDecodeError as e: - err_out_screen( - "Improper WindBiasCorrection options specified in the configuration file.", - e, - ) - if len(self.windBiasCorrect) != self.number_inputs: - err_out_screen( - "Please specify WindBiasCorrection values for each corresponding input forcings in the configuration file." - ) - # Ensure the bias correction options chosen make sense. - for optTmp in self.windBiasCorrect: - if optTmp < 0 or optTmp > 4: - err_out_screen( - "Invalid WindBiasCorrection options specified in the configuration file." - ) - if optTmp == 1: - # We are running NWM-Specific bias-correction of CFSv2 that needs to take place prior to regridding. - self.runCfsNldasBiasCorrect = True + @swBiasCorrectOpt.setter + def swBiasCorrectOpt(self, value: list) -> None: + """Set the list of shortwave radiation bias correction options specified by the user in the configuration file. This is used to control how shortwave radiation input forcings are bias corrected based on the shortwave radiation bias correction option specified for each input forcing in the configuration file.""" + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "SwBiasCorrection") + self.check_input_values_in_range(value, "SwBiasCorrection", [0, 1, 2]) + self._swBiasCorrectOpt = value - # Read in shortwave radiation bias correction options. - try: - self.swBiasCorrectOpt = cfg_bmi["SwBiasCorrection"] - except KeyError as e: - err_out_screen( - "Unable to locate SwBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate SwBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except json.JSONDecodeError as e: - err_out_screen( - "Improper SwBiasCorrection options specified in the configuration file.", - e, - ) - if len(self.swBiasCorrectOpt) != self.number_inputs: - err_out_screen( - "Please specify SwBiasCorrection values for each corresponding input forcings in the configuration file." - ) - # Ensure the bias correction options chosen make sense. - for optTmp in self.swBiasCorrectOpt: - if optTmp < 0 or optTmp > 2: - err_out_screen( - "Invalid SwBiasCorrection options specified in the configuration file." - ) - if optTmp == 1: - # We are running NWM-Specific bias-correction of CFSv2 that needs to take place prior to regridding. - self.runCfsNldasBiasCorrect = True + @property + def lwBiasCorrectOpt(self) -> list: + """Specify a bias correction for incoming long wave radiation flux. 0 - No bias correction, 1 - CFSv2 - NLDAS2 Parametric Distribution - NWM ONLY, 2 - Custom NCAR bias-correction based on HRRRv3 analysis, blanket adjustment (USE WITH CAUTION), 3 - NCAR parametric GFS bias correction. - # Read in longwave radiation bias correction options. - try: - self.lwBiasCorrectOpt = cfg_bmi["LwBiasCorrection"] - except KeyError as e: - err_out_screen( - "Unable to locate LwBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate LwBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except json.JSONDecodeError as e: - err_out_screen( - "Improper LwBiasCorrection options specified in the configuration file.", - e, - ) - if len(self.lwBiasCorrectOpt) != self.number_inputs: - err_out_screen( - "Please specify LwBiasCorrection values for each corresponding input forcings in the configuration file." - ) - # Ensure the bias correction options chosen make sense. - for optTmp in self.lwBiasCorrectOpt: - if optTmp < 0 or optTmp > 4: - err_out_screen( - "Invalid LwBiasCorrection options specified in the configuration file." - ) - if optTmp == 1: - # We are running NWM-Specific bias-correction of CFSv2 that needs to take place prior to regridding. - self.runCfsNldasBiasCorrect = True + Example- LwBiasCorrection: [0, 2] + """ + return self._lwBiasCorrectOpt + + @lwBiasCorrectOpt.setter + def lwBiasCorrectOpt(self, value: list) -> None: + """Set the list of longwave radiation bias correction options specified by the user in the configuration file. This is used to control how longwave radiation input forcings are bias corrected based on the longwave radiation bias correction option specified for each input forcing in the configuration file.""" + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "LwBiasCorrection") + self.check_input_values_in_range(value, "LwBiasCorrection", [0, 1, 2, 3, 4]) + self._lwBiasCorrectOpt = value + + @property + def precipBiasCorrectOpt(self): + """Specify a bias correction for precipitation. 0 - No bias correction, 1 - CFSv2 - NLDAS2 Parametric Distribution - NWM ONLY. - # Read in precipitation bias correction options. - try: - self.precipBiasCorrectOpt = cfg_bmi["PrecipBiasCorrection"] - except KeyError as e: - err_out_screen( - "Unable to locate PrecipBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate PrecipBiasCorrection under the BiasCorrection section of the configuration file.", - e, - ) - except json.JSONDecodeError as e: - err_out_screen( - "Improper PrecipBiasCorrection options specified in the configuration file.", - e, - ) - if not self.precip_only_flag: - if len(self.precipBiasCorrectOpt) != self.number_inputs: - err_out_screen( - "Please specify PrecipBiasCorrection values for each corresponding input forcings in the configuration file." - ) - # Ensure the bias correction options chosen make sense. - for optTmp in self.precipBiasCorrectOpt: - if optTmp < 0 or optTmp > 1: - err_out_screen( - "Invalid PrecipBiasCorrection options specified in the configuration file." - ) - if optTmp == 1: - # We are running NWM-Specific bias-correction of CFSv2 that needs to take place prior to regridding. - self.runCfsNldasBiasCorrect = True - - # Putting a constraint here that CFSv2-NLDAS bias correction (NWM only) is chosen, it must be turned on - # for ALL variables. - if self.runCfsNldasBiasCorrect: - if ( - min(self.precipBiasCorrectOpt) != 1 - and max(self.precipBiasCorrectOpt) != 1 - ): - err_out_screen( - "CFSv2-NLDAS NWM bias correction must be activated for Precipitation under this configuration." - ) - if min(self.lwBiasCorrectOpt) != 1 and max(self.lwBiasCorrectOpt) != 1: - err_out_screen( - "CFSv2-NLDAS NWM bias correction must be activated for long-wave radiation under this configuration." - ) - if min(self.swBiasCorrectOpt) != 1 and max(self.swBiasCorrectOpt) != 1: - err_out_screen( - "CFSv2-NLDAS NWM bias correction must be activated for short-wave radiation under this configuration." - ) - if min(self.t2BiasCorrectOpt) != 1 and max(self.t2BiasCorrectOpt) != 1: - err_out_screen( - "CFSv2-NLDAS NWM bias correction must be activated for surface temperature under this configuration." - ) - if min(self.windBiasCorrect) != 1 and max(self.windBiasCorrect) != 1: - err_out_screen( - "CFSv2-NLDAS NWM bias correction must be activated for wind forcings under this configuration." - ) - if min(self.q2BiasCorrectOpt) != 1 and max(self.q2BiasCorrectOpt) != 1: - err_out_screen( - "CFSv2-NLDAS NWM bias correction must be activated for specific humidity under this configuration." - ) - if ( - min(self.psfcBiasCorrectOpt) != 1 - and max(self.psfcBiasCorrectOpt) != 1 - ): + Example- PrecipBiasCorrection: [0, 0] + """ + return self._precipBiasCorrectOpt + + @precipBiasCorrectOpt.setter + def precipBiasCorrectOpt(self, value): + """Set the list of precipitation bias correction options specified by the user in the configuration file. This is used to control how precipitation input forcings are bias corrected based on the precipitation bias correction option specified for each input forcing in the configuration file.""" + if not self.precip_only_flag: + self.check_number_of_inputs_forcings(value, "PrecipBiasCorrection") + self.check_input_values_in_range(value, "PrecipBiasCorrection", [0, 1]) + self._precipBiasCorrectOpt = value + + @property + def bias_correction_properties(self) -> dict: + """Get the dictionary of bias correction properties specified by the user in the configuration file. This is used to control how input forcings are bias corrected based on the bias correction options specified for each input forcing in the configuration file.""" + return { + # "surface temperature": self.t2BiasCorrectOpt, #NOTE surface temperature was excluded from this consideration in the orignal code (5/7/2026 pre-refactor). Should it actually be included? + "surface pressure": self.psfcBiasCorrectOpt, + "specific humidity": self.q2BiasCorrectOpt, + "wind forcings": self.windBiasCorrect, + "short-wave radiation": self.swBiasCorrectOpt, + "long-wave radiation": self.lwBiasCorrectOpt, + "Precipitation": self.precipBiasCorrectOpt, + } + + @property + def runCfsNldasBiasCorrect(self) -> bool: + """Get the flag for whether to run the NWM-specific bias correction of CFSv2 input forcings specified by the user in the configuration file. This is used to control whether the NWM-specific bias correction of CFSv2 input forcings is run based on whether the user has chosen to run this bias correction in the configuration file.""" + run_cfs_nldas_bias_correct = False + for bias_option in self.bias_correction_properties.values(): + for opt in bias_option: + if opt == 1: + run_cfs_nldas_bias_correct = True + break + if run_cfs_nldas_bias_correct: + for ( + bias_correct_name, + bias_correct, + ) in self.bias_correction_properties.items(): + if min(bias_correct) != 1 and max(bias_correct) != 1: err_out_screen( - "CFSv2-NLDAS NWM bias correction must be activated for surface pressure under this configuration." + f"CFSv2-NLDAS NWM bias correction must be activated for {bias_correct_name} under this configuration." ) # Make sure we don't have any other forcings activated. This can only be ran for CFSv2. for opt_tmp in self.input_forcings: @@ -1700,424 +1278,266 @@ def validate_config(self, cfg_bmi: dict) -> None: err_out_screen( "CFSv2-NLDAS NWM bias correction can only be used in CFSv2-only configurations" ) + return run_cfs_nldas_bias_correct - # Read in supplemental precipitation options as an array of values to map. - try: - self.supp_precip_forcings = cfg_bmi["SuppPcp"] - except KeyError as e: - err_out_screen( - "Unable to locate SuppPcp under SuppForcing section in configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate SuppPcp under SuppForcing section in configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen("Improper SuppPcp option specified in configuration file", e) - self.number_supp_pcp = len(self.supp_precip_forcings) + @property + def number_supp_pcp(self) -> int: + """Get the number of supplemental precipitation input forcings specified by the user in the configuration file. This is used to control how many supplemental precipitation input forcings are processed based on the number of supplemental precipitation input forcings specified in the configuration file.""" + return len(self.supp_precip_forcings) - # Read in the supp pcp types (GRIB[1|2], NETCDF) - try: - self.supp_precip_file_types = cfg_bmi["SuppPcpForcingTypes"] - self.supp_precip_file_types = [ - stype.strip() for stype in self.supp_precip_file_types - ] - if self.supp_precip_file_types == [""]: - self.supp_precip_file_types = [] - except KeyError as e: - err_out_screen( - "Unable to locate SuppPcpForcingTypes in SuppForcing section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate SuppPcpForcingTypes in SuppForcing section in the configuration file.", - e, - ) - if len(self.supp_precip_file_types) != self.number_supp_pcp: - err_out_screen( - "Number of SuppPcpForcingTypes ({}) must match the number " - "of SuppPcp inputs ({}) in the configuration file.".format( - len(self.supp_precip_file_types), self.number_supp_pcp - ) - ) - for file_type in self.supp_precip_file_types: - if file_type not in ["GRIB1", "GRIB2", "NETCDF"]: - err_out_screen( - 'Invalid SuppForcing file type "{}" specified. ' - "Only GRIB1, GRIB2, and NETCDF are supported".format(file_type) - ) + @property + def supp_precip_file_types(self) -> list: + """Get the list of supplemental precipitation input forcing file types specified by the user in the configuration file. This is used to control how supplemental precipitation input forcing files are read in and processed based on the file types specified for each supplemental precipitation input forcing in the configuration file.""" + return self._supp_precip_file_types + + @supp_precip_file_types.setter + def supp_precip_file_types(self, value: list) -> None: + """Set the list of supplemental precipitation input forcing file types specified by the user in the configuration file. This is used to control how supplemental precipitation input forcing files are read in and processed based on the file types specified for each supplemental precipitation input forcing in the configuration file.""" + if value is not None: + value = [stype.strip() for stype in value] + if value == [""]: + value = [] + self.check_number_of_inputs_supp_pcp(value, "SuppPcpForcingTypes") + self.check_input_values_in_range( + value, + "SuppPcpForcingTypes", + self.supplemental_precip_file_type_options, + ) + self._supp_precip_file_types = value + + @property + def supplemental_precip_file_type_options(self) -> list: + """Get the list of valid supplemental precipitation input forcing file types that can be specified by the user in the configuration file. This is used to control how supplemental precipitation input forcing files are read in and processed based on the file types specified for each supplemental precipitation input forcing in the configuration file.""" + return ["GRIB1", "GRIB2", "NETCDF"] + + @property + def rqiMethod(self) -> list: + """Optional RQI method for radar-based data. 0 - Do not use any RQI filtering. Use all radar-based estimates. 1 - Use hourly MRMS Radar Quality Index grids, 2 - Use NWM monthly climatology grids (NWM only!!!!). + Example- RqiMethod: 2 + """ + value = None if self.number_supp_pcp > 0: - # Check to make sure supplemental precip options make sense. Also read in the RQI threshold - # if any radar products where chosen. for suppOpt in self.supp_precip_forcings: - if suppOpt < 0 or suppOpt > 16: - err_out_screen( - "Please specify SuppForcing values between 1 and 16." - ) # Read in RQI threshold to apply to radar products. if suppOpt in (1, 2, 7, 10, 11, 12): - try: - self.rqiMethod = cfg_bmi["RqiMethod"] - except KeyError as e: - err_out_screen( - "Unable to locate RqiMethod under SuppForcing section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate RqiMethod under SuppForcing section in the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper RqiMethod option in the configuration file.", e - ) + value = self.extract_input_variable("RqiMethod") # Check that if we have more than one RqiMethod, it's the correct number - if type(self.rqiMethod) is list: - if len(self.rqiMethod) != self.number_supp_pcp: - err_out_screen( - "Number of RqiMethods ({}) must match the number " - "of SuppPcp inputs ({}) in the configuration file, or " - "supply a single method for all inputs".format( - len(self.rqiMethod), self.number_supp_pcp - ) - ) - elif type(self.rqiMethod) is int: + if isinstance(value, list): + self.check_number_of_inputs_supp_pcp(value, "RqiMethod") + elif isinstance(value, int): # Support 'classic' mode of single method - self.rqiMethod = [self.rqiMethod] * self.number_supp_pcp - + value = [value] * self.number_supp_pcp + else: + raise TypeError( + f"Invalide type ({type(value)}) specified for RqiMethod; expected list or int." + ) # Make sure the RqiMethod(s) makes sense. - for method in self.rqiMethod: - if method < 0 or method > 2: - err_out_screen( - "Please specify RqiMethods of either 0, 1, or 2." - ) + self.check_input_values_in_range(value, "RqiMethod", [0, 1, 2]) + return value - try: - self.rqiThresh = cfg_bmi["RqiThreshold"] - except KeyError as e: - err_out_screen( - "Unable to locate RqiThreshold under SuppForcing section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate RqiThreshold under SuppForcing section in the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper RqiThreshold option in the configuration file.", e - ) + @property + def rqiThresh(self): + """Optional RQI threshold to be used to mask out. Currently used for MRMS products. Please choose a value from 0.0-1.0. Associated radar quality index files will be expected from MRMS data. - # Check that if we have more than one RqiThreshold, it's the correct number - if type(self.rqiThresh) is list: - if len(self.rqiThresh) != self.number_supp_pcp: - err_out_screen( - "Number of RqiThresholds ({}) must match the number " - "of SuppPcp inputs ({}) in the configuration file, or " - "supply a single threshold for all inputs".format( - len(self.rqiThresh), self.number_supp_pcp - ) - ) - elif type(self.rqiThresh) is float: + Example- RqiThreshold: 0.9 + """ + value = 1.0 + if self.number_supp_pcp > 0: + for supp_opt in self.supp_precip_forcings: + # Read in RQI threshold to apply to radar products. + if supp_opt in (1, 2, 7, 10, 11, 12): + value = self.extract_input_variable("RqiThreshold") + + # Check that if we have more than one RqiThresh, it's the correct number + if isinstance(value, list): + self.check_number_of_inputs_supp_pcp(value, "RqiThreshold") + elif isinstance(value, (int, float)): # Support 'classic' mode of single threshold - self.rqiThresh = [self.rqiThresh] * self.number_supp_pcp + value = [value] * self.number_supp_pcp + else: + raise TypeError( + f"Invalid type ({type(value)}) specified for RqiThreshold; expected list, float, or int" + ) - # Make sure the RQI threshold makes sense. - for threshold in self.rqiThresh: + # Make sure the RqiThresh(es) makes sense. + for threshold in value: if threshold < 0.0 or threshold > 1.0: err_out_screen( "Please specify RqiThresholds between 0.0 and 1.0." ) + return value - # Read in the input directories for each supplemental precipitation product. - try: - self.supp_precip_dirs = cfg_bmi["SuppPcpDirectories"] - except KeyError as e: - err_out_screen( - "Unable to locate SuppPcpDirectories in SuppForcing section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate SuppPcpDirectories in SuppForcing section in the configuration file.", - e, - ) + @property + def supp_precip_mandatory(self): + """Specify whether the Supplemental Precips listed above are mandatory, or optional. This is important for layering contingencies if a product is missing, but forcing files are still desired. 0 - Not mandatory, 1 - Mandatory. - # Loop through and ensure all supp pcp directories exist. Also strip out any whitespace - # or new line characters. - for dirTmp in range(0, len(self.supp_precip_dirs)): - self.supp_precip_dirs[dirTmp] = self.supp_precip_dirs[dirTmp].strip() - if not os.path.isdir(self.supp_precip_dirs[dirTmp]): - try: - os.makedirs(self.supp_precip_dirs[dirTmp], exist_ok=True) - LOG.debug( - f"Created supp pcp directory: {self.supp_precip_dirs[dirTmp]}" - ) - except OSError as e: - err_out_screen( - f"Unable to create supp pcp directory: {self.supp_precip_dirs[dirTmp]}. Error: {e}" - ) + Example- SuppPcpMandatory: [0, 0, 0] + """ + return self._supp_precip_mandatory - # Special case for ExtAnA where we treat comma separated stage IV, MRMS data as one SuppPcp input - if 11 in self.supp_precip_forcings or 12 in self.supp_precip_forcings: - if len(self.supp_precip_forcings) != 1: - err_out_screen( - "CONUS or Alaska Stage IV/MRMS SuppPcp option is only supported as a standalone option" - ) - self.supp_precip_dirs = [",".join(self.supp_precip_dirs)] + @supp_precip_mandatory.setter + def supp_precip_mandatory(self, value): + """Set the list of flags for whether each supplemental precipitation input forcing specified by the user in the configuration file is mandatory or optional. This is used to control whether an error is raised if supplemental precipitation input forcing files are not found for each supplemental precipitation input forcing based on whether the user has specified each supplemental precipitation input forcing as mandatory or optional in the configuration file.""" + if self.number_supp_pcp > 0: + self.check_input_values_in_range(value, "SuppPcpMandatory", [0, 1]) + self._supp_precip_mandatory = value + else: + self._supp_precip_mandatory = None - if len(self.supp_precip_dirs) != self.number_supp_pcp: - err_out_screen( - "Number of SuppPcpDirectories must match the number of SuppForcing in the configuration file." - ) + @property + def regrid_opt_supp_pcp(self): + """Specify regridding options for the supplemental precipitation products. Options available are: 1 - ESMF Bilinear, 2 - ESMF Nearest Neighbor, 3 - ESMF Conservative Bilinear. - # Process supplemental precipitation enforcement options - try: - self.supp_precip_mandatory = cfg_bmi["SuppPcpMandatory"] - except KeyError as e: - err_out_screen( - "Unable to locate SuppPcpMandatory under the SuppForcing section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate SuppPcpMandatory under the SuppForcing section in the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper SuppPcpMandatory options specified in the configuration file.", - e, - ) - if len(self.supp_precip_mandatory) != self.number_supp_pcp: - err_out_screen( - "Please specify SuppPcpMandatory values for each corresponding " - "supplemental precipitation options in the configuration file." - ) - # Check to make sure enforcement options makes sense. - for enforceOpt in self.supp_precip_mandatory: - if enforceOpt < 0 or enforceOpt > 1: - err_out_screen( - "Invalid SuppPcpMandatory chosen in the configuration file. " - "Please choose a value of 0 or 1 for each corresponding " - "supplemental precipitation product." - ) + Example- RegridOptSuppPcp: [1, 1, 1] + """ + return self._regrid_opt_supp_pcp - # Read in the regridding options. - try: - self.regrid_opt_supp_pcp = cfg_bmi["RegridOptSuppPcp"] - except KeyError as e: - err_out_screen( - "Unable to locate RegridOptSuppPcp under the SuppForcing section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate RegridOptSuppPcp under the SuppForcing section in the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper RegridOptSuppPcp options specified in the configuration file.", - e, - ) - if len(self.regrid_opt_supp_pcp) != self.number_supp_pcp: - err_out_screen( - "Please specify RegridOptSuppPcp values for each corresponding supplemental " - "precipitation product in the configuration file." - ) - # Check to make sure regridding options makes sense. - for regridOpt in self.regrid_opt_supp_pcp: - if regridOpt < 1 or regridOpt > 3: - err_out_screen( - "Invalid RegridOptSuppPcp chosen in the configuration file. " - "Please choose a value of 1-3 for each corresponding " - "supplemental precipitation product." - ) + @regrid_opt_supp_pcp.setter + def regrid_opt_supp_pcp(self, value): + """Set the list of regridding options for supplemental precipitation input forcings specified by the user in the configuration file. This is used to control how supplemental precipitation input forcings are regridded based on the regridding option specified for each supplemental precipitation input forcing in the configuration file.""" + if self.number_supp_pcp > 0: + self.check_input_values_in_range(value, "RegridOptSuppPcp", [1, 2, 3]) + self._regrid_opt_supp_pcp = value + else: + self._regrid_opt_supp_pcp = None - # Read in temporal interpolation options. - try: - self.suppTemporalInterp = cfg_bmi["SuppPcpTemporalInterpolation"] - except KeyError as e: - err_out_screen( - "Unable to locate SuppPcpTemporalInterpolation under the SuppForcing section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate SuppPcpTemporalInterpolation under the SuppForcing section in the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper SuppPcpTemporalInterpolation options specified in the configuration file.", - e, - ) - if len(self.suppTemporalInterp) != self.number_supp_pcp: - err_out_screen( - "Please specify SuppPcpTemporalInterpolation values for each " - "corresponding supplemental precip products in the configuration file." - ) - # Ensure the SuppPcpTemporalInterpolation values make sense. - for temporalInterpOpt in self.suppTemporalInterp: - if temporalInterpOpt < 0 or temporalInterpOpt > 2: - err_out_screen( - "Invalid SuppPcpTemporalInterpolation chosen in the configuration file. " - "Please choose a value of 0-2 for each corresponding input forcing" - ) + @property + def suppTemporalInterp(self): + """Specify the time interpretation methods for the supplemental precipitation products. - # Read in max time option - try: - self.supp_pcp_max_hours = cfg_bmi["SuppPcpMaxHours"] - except (KeyError, configparser.NoOptionError): - self.supp_pcp_max_hours = ( - None # if missing, don't care, just assume all time - ) + Example- SuppPcpTemporalInterpolation: [0, 0, 0] + """ + return self._suppTemporalInterp - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper SuppPcpMaxHours options specified in the configuration file.", - e, - ) + @suppTemporalInterp.setter + def suppTemporalInterp(self, value): + """Set the list of flags for whether temporal interpolation of supplemental precipitation input forcings specified by the user in the configuration file is performed or not. This is used to control whether temporal interpolation of supplemental precipitation input forcings is performed based on whether the user has chosen to perform temporal interpolation for each supplemental precipitation input forcing in the configuration file.""" + if self.number_supp_pcp > 0: + self.check_input_values_in_range( + value, "SuppPcpTemporalInterpolation", [0, 1, 2] + ) + self._suppTemporalInterp = value + else: + self._suppTemporalInterp = None - if type(self.supp_pcp_max_hours) is list: - if len(self.supp_pcp_max_hours) != self.number_supp_pcp: - err_out_screen( - "Number of SuppPcpMaxHours ({}) must match the number " - "of SuppPcp inputs ({}) in the configuration file, or " - "supply a single threshold for all inputs".format( - len(self.supp_pcp_max_hours), self.number_supp_pcp - ) - ) - elif type(self.supp_pcp_max_hours) is float: - # Support 'classic' mode of single threshold - self.supp_pcp_max_hours = [ - self.supp_pcp_max_hours - ] * self.number_supp_pcp + @property + def supp_pcp_max_hours(self): + """Get the list of maximum forecast hours for supplemental precipitation input forcings specified by the user in the configuration file. This is used to control how supplemental precipitation input forcings are processed based on the maximum forecast hour specified for each supplemental precipitation input forcing in the configuration file.""" + return self._supp_pcp_max_hours - # Read in the SuppPcpInputOffsets options. - try: - self.supp_input_offsets = cfg_bmi["SuppPcpInputOffsets"] - except KeyError as e: - err_out_screen( - "Unable to locate SuppPcpInputOffsets under SuppForcing section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate SuppPcpInputOffsets under SuppForcing section in the configuration file.", - e, - ) - except json.decoder.JSONDecodeError as e: - err_out_screen( - "Improper SuppPcpInputOffsets option specified in the configuration file.", - e, - ) - if len(self.supp_input_offsets) != self.number_supp_pcp: - err_out_screen( - "Please specify SuppPcpInputOffsets values for each " - "corresponding input forcings for SuppForcing." - ) - # Check to make sure the input offset options make sense. There will be additional - # checking later when input choices are mapped to input products. - for inputOffset in self.supp_input_offsets: - if inputOffset < 0: - err_out_screen( - "Please specify SuppPcpInputOffsets values greater than or equal to zero." - ) + @supp_pcp_max_hours.setter + def supp_pcp_max_hours(self, value): + """Set the list of maximum forecast hours for supplemental precipitation input forcings specified by the user in the configuration file. This is used to control how supplemental precipitation input forcings are processed based on the maximum forecast hour specified for each supplemental precipitation input forcing in the configuration file.""" + if self.number_supp_pcp > 0: + if isinstance(value, list): + self.check_number_of_inputs_supp_pcp(value, "SuppPcpMaxHours") + elif isinstance(value, float) or isinstance(value, int): + value = [value] * self.number_supp_pcp + self._supp_pcp_max_hours = value + else: + self._supp_pcp_max_hours = None - # Read in the optional parameter directory for supplemental precipitation. - try: - self.supp_precip_param_dir = cfg_bmi["SuppPcpParamDir"] - except KeyError as e: - err_out_screen( - "Unable to locate SuppPcpParamDir under the SuppForcing section in the configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate SuppPcpParamDir under the SuppForcing section in the configuration file.", - e, - ) - except ValueError as e: - err_out_screen( - "Improper SuppPcpParamDir option specified in the configuration file.", - e, - ) - if not os.path.isdir(self.supp_precip_param_dir): - try: - os.makedirs(self.supp_precip_param_dir, exist_ok=True) - LOG.debug( - f"Created missing SuppPcpParamDir: {self.supp_precip_param_dir}" - ) - except OSError as e: + @property + def supp_input_offsets(self): + """In AnA runs, this value is the offset from the available forecast and 00z. For example, if forecast are available at 06z and 18z, set this value to 6. + + Example- SuppPcpInputOffsets = [0, 0, 0] + """ + return self._supp_input_offsets + + @supp_input_offsets.setter + def supp_input_offsets(self, value): + """Set the list of time offsets to apply to supplemental precipitation input forcing files specified by the user in the configuration file. This is used to control how supplemental precipitation input forcing files are processed based on the time offset specified for each supplemental precipitation input forcing in the configuration file.""" + if self.number_supp_pcp > 0: + self.check_number_of_inputs_supp_pcp(value, "SuppPcpInputOffsets") + self._supp_input_offsets = value + else: + self._supp_input_offsets = None + + @property + def supp_precip_dirs(self): + """Specify the correponding supplemental precipitation directories that will be searched for input files. + + Example- SuppPcpDirectories: ['./MRMS_CONUS_GAUGE', './MRMS_CONUS_MULTISENSOR', './MRMS_CLASSIFICATION'] + """ + return self._supp_precip_dirs + + @supp_precip_dirs.setter + def supp_precip_dirs(self, value): + """Set the list of pathways to the supplemental precipitation input forcing directories specified by the user in the configuration file. This is used to control where the program looks for supplemental precipitation input forcing files for each supplemental precipitation input forcing based on the directory specified for each supplemental precipitation input forcing in the configuration file.""" + if self.number_supp_pcp > 0: + self.check_number_of_inputs_supp_pcp(value, "SuppPcpDirectories") + # Loop through and ensure all supp pcp directories exist. Also strip out any whitespace + # or new line characters. + for dirTmp in range(0, len(value)): + value[dirTmp] = value[dirTmp].strip() + self.try_make_dir(value[dirTmp], " supp pcp") + + # Special case for ExtAnA where we treat comma separated stage IV, MRMS data as one SuppPcp input + if 11 in self.supp_precip_forcings or 12 in self.supp_precip_forcings: + if len(self.supp_precip_forcings) != 1: err_out_screen( - f"Unable to locate SuppPcpParamDir: {self.supp_precip_param_dir}. Error: {e}" + "CONUS or Alaska Stage IV/MRMS SuppPcp option is only supported as a standalone option" ) + value = [",".join(value)] + self._supp_precip_dirs = value + else: + self._supp_precip_dirs = None + @property + def supp_precip_param_dir(self): + """Specify an optional directory that contains supplemental precipitation parameter fields, I.E monthly RQI climatology. This is ONLY needed for the original NWM WRF-Hydro domain. Otherwise, just point it to a random directory and it will be ignored. + + Example- SuppPcpParamDir: ['./forcingParam/AnA','./forcingParam/AnA','./forcingParam/AnA'] + """ + return self._supp_precip_param_dir + + @supp_precip_param_dir.setter + def supp_precip_param_dir(self, value): + """Set the directory where downscaling parameters for supplemental precipitation input forcings are stored specified by the user in the configuration file. This is used to control where the program looks for downscaling parameter files for supplemental precipitation input forcings based on the directory specified for supplemental precipitation input forcings in the configuration file.""" + if self.number_supp_pcp > 0: + self.try_make_dir(value, " SuppPcpParamDir") + self._supp_precip_param_dir = value + else: + self._supp_precip_param_dir = None + + @property + def cfsv2EnsMember(self): + """Set the CFSv2 ensemble member to process specified by the user in the configuration file. This is used to control which CFSv2 ensemble member is processed for CFSv2 input forcings based on the ensemble member specified in the configuration file.""" + value = None if not self.precip_only_flag: # Read in Ensemble information # Read in CFS ensemble member information IF we have chosen CFSv2 as an input # forcing. for opt_tmp in self.input_forcings: if opt_tmp == 7: - try: - self.cfsv2EnsMember = cfg_bmi["cfsEnsNumber"] - LOG.debug(f"ens mem: {self.cfsv2EnsMember}") - LOG.debug(f"cfg ens mem: {cfg_bmi['cfsEnsNumber']}") - except KeyError as e: - err_out_screen( - "Unable to locate cfsEnsNumber under the Ensembles section of the configuration file", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate cfsEnsNumber under the Ensembles section of the configuration file", - e, - ) - except json.JSONDecodeError as e: - err_out_screen( - "Improper cfsEnsNumber options specified in the configuration file", - e, - ) - if int(self.cfsv2EnsMember) < 1 or int(self.cfsv2EnsMember) > 4: - err_out_screen( - "Please chose an cfsEnsNumber value of 1,2,3 or 4." - ) + value = self.extract_input_variable("cfsEnsNumber") + self.check_input_values_in_range( + value, "cfsEnsNumber", [1, 2, 3, 4] + ) + return value - # Read in information for the custom input NetCDF files that are to be processed. - # Read in the ForecastInputHorizons options. - try: - self.customFcstFreq = cfg_bmi["custom_input_fcst_freq"] - except KeyError as e: - err_out_screen( - "Unable to locate custom_input_fcst_freq under Custom section in configuration file.", - e, - ) - except configparser.NoOptionError as e: - err_out_screen( - "Unable to locate custom_input_fcst_freq under Custom section in configuration file.", - e, - ) - except json.decoder.JSONDecodeError as je: - err_out_screen( - "Improper custom_input_fcst_freq option specified in configuration file: " - + str(je) - ) - if len(self.customFcstFreq) != self.number_custom_inputs: + @property + def customFcstFreq(self): + """Get the custom forecast frequency in minutes specified by the user in the configuration file. This is used to control how often forecasts are issued based on the custom forecast frequency specified in the configuration file.""" + return self._customFcstFreq + + @customFcstFreq.setter + def customFcstFreq(self, value): + """Options for specifying custom input NetCDF forcing files (in minutes). Choose the input frequency of files that are being processed. I.E., are the input files every 15 minutes, 60 minutes, 3-hours, etc. Please specify the length of custom input frequencies to match the number of custom NetCDF inputs selected above in the Logistics section. + + Example- custom_input_fcst_freq: [] + """ + if not self.precip_only_flag: + if len(value) != self.number_custom_inputs: err_out_screen( - f"Improper custom_input fcst_freq specified. " - f"This number ({len(self.customFcstFreq)}) must " - f"match the frequency of custom input forcings selected " - f"({self.number_custom_inputs})." + f"Improper custom_input fcst_freq specified. This number ({len(value)}) must match the frequency of custom input forcings selected ({self.number_custom_inputs})." ) + self._customFcstFreq = value + else: + self._customFcstFreq = None @property def nwm_domain(self) -> str: diff --git a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/consts.py b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/consts.py index 2fd37fe1..8761edc4 100644 --- a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/consts.py +++ b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/consts.py @@ -9,6 +9,22 @@ ) BMI_MODEL = { + "NWMv3_Forcing_Engine_BMI_model_Base": [ + "_model", + "_comm", + "cfg_bmi", + "_job_meta", + "_mpi_meta", + "_geo_meta", + "_grids", + "_grid_map", + "_output_var_names", + "_var_name_units_map", + "_input_forcing_mod", + "_supp_pcp_mod", + "_output_obj", + "_total_start", + ], "att_map": { "model_name": "NWMv3.0 Forcings Engine BMI Python", "version": "1.0", @@ -1005,6 +1021,22 @@ "precipBiasCorrectOpt", ], } + +MODEL = { + # Used by method `model.NWMv3ForcingEngineModel.update_bmi_output_dict` + "update_dict_base_vars": [ + "U2D", + "V2D", + "LWDOWN", + "RAINRATE", + "T2D", + "Q2D", + "PSFC", + "SWDOWN", + ], + "update_dict_var_include_lqfraq": "LQFRAC", +} + TEST_UTILS = { "OLD_NEW_VAR_MAP": { "q2dBiasCorrectOpt": "q2BiasCorrectOpt", @@ -1022,3 +1054,108 @@ "file_type": "input_force_types", } } + +CONFIGOPTIONS = { + "ConfigOptions": [ + "bmi_time", + "current_time", + "e_date_proc", + "first_fcst_cycle", + "current_fcst_cycle", + "current_output_step", + "prev_output_date", + "current_output_date", + "future_time", + "nFcsts", + "process_window", + "grid_meta", + "ExactExtract", + "errMsg", + "statusMsg", + "logFile", + "logHandle", + "paramFlagArray", + "nwmVersion", + "nwmConfig", + "forcing_output", + "aws", + "aws_obj", + "aws_time", + "nwm_geogrid", + "geopackage", + "uid64", + ], + "var_rename_map": {"config_path": "cfg_bmi"}, + "extract_input_variable_attrs_map": { + "OutputFrequency": "output_freq", + "SubOutputHour": "sub_output_hour", + "SubOutFreq": "sub_output_freq", + "ScratchDir": "scratch_dir", + "compressOutput": "useCompression", # 0 + "AnAFlag": "ana_flag", + "ForecastFrequency": "fcst_freq", + "ForecastShift": "fcst_shift", + "LookBack": "look_back", + "GRID_TYPE": "grid_type", + "DownscalingParamDirs": "dScaleParamDirs", + "SuppPcpDirectories": "supp_precip_dirs", + "SuppPcpMandatory": "supp_precip_mandatory", + "RegridOptSuppPcp": "regrid_opt_supp_pcp", + "SuppPcpTemporalInterpolation": "suppTemporalInterp", + "SuppPcpInputOffsets": "supp_input_offsets", + "SuppPcpParamDir": "supp_precip_param_dir", + "SuppPcpForcingTypes": "supp_precip_file_types", + }, + "extract_input_variable_attrs_map_precip_only": { + "customSuppPcpFreq": "customSuppPcpFreq", + }, + "extract_input_variable_attrs_map_not_precip_only": { + "ForecastInputHorizons": "fcst_input_horizons", # np + "ForecastInputOffsets": "fcst_input_offsets", # np + "IgnoredBorderWidths": "ignored_border_widths", # np + "RegridOpt": "regrid_opt", # np + "ForcingTemporalInterpolation": "forceTemoralInterp", # np + "TemperatureDownscaling": "t2dDownscaleOpt", # np + "PressureDownscaling": "psfcDownscaleOpt", # np + "ShortwaveDownscaling": "swDownscaleOpt", # np + "HumidityDownscaling": "q2dDownscaleOpt", # np + "PrecipDownscaling": "precipDownscaleOpt", # np -complicated partial np + "TemperatureBiasCorrection": "t2BiasCorrectOpt", # np #no + "PressureBiasCorrection": "psfcBiasCorrectOpt", # np #yes + "HumidityBiasCorrection": "q2BiasCorrectOpt", # np #yes + "WindBiasCorrection": "windBiasCorrect", # np #yes + "SwBiasCorrection": "swBiasCorrectOpt", # np #yes + "LwBiasCorrection": "lwBiasCorrectOpt", # np #yes + "PrecipBiasCorrection": "precipBiasCorrectOpt", # np #yes + "InputForcingTypes": "input_force_types", # np + "InputForcingDirectories": "input_force_dirs", # np + "InputMandatory": "input_force_mandatory", # np + "custom_input_fcst_freq": "customFcstFreq", # np + }, + "downscaling_attrs_map": { + "SINALPHA": "sinalpha_var", + "COSALPHA": "cosalpha_var", + "SLOPE": "slope_var", + "SLOPE_AZIMUTH": "slope_azimuth_var", + "HGT": "hgt_var", + }, + "downscaling_unstructred_attrs_map": { + "SLOPE_ELEM": "slope_var_elem", + "SLOPE_AZIMUTH_ELEM": "slope_azimuth_var_elem", + "HGT_ELEM": "hgt_elem_var", + }, + "extract_input_variable_set_default_attrs_map": { + "includeLQFrac": "include_lqfrac", + "floatOutput": "useFloats", + "Output": "forcing_output", + "SuppPcpMaxHours": "supp_pcp_max_hours", + "RegridWeightsDir": "weightsDir", # np + }, + "try_config_get_except_attr_map": { + "RefcstBDateProc": "b_date_proc", + "Geopackage": "geopackage", + "GeogridIn": "geogrid", + "SpatialMetaIn": "spatial_meta", + }, + "file_types": ["GRIB1", "GRIB2", "NETCDF", "NETCDF4", "NWM", "ZARR", "GRIB2_CFS"], +} diff --git a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/forcingInputMod.py b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/forcingInputMod.py index 356c04cb..1cb97ef7 100755 --- a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/forcingInputMod.py +++ b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/forcingInputMod.py @@ -93,7 +93,8 @@ def _initialize_config_options(self) -> None: Check if the attibute allready exists before setting. """ - for key, val in list(vars(self.config_options).items()): + for key in dir(self.config_options): + val=getattr(self.config_options,key) if ( isinstance(val, list) and len(val) > 0 diff --git a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/geoMod.py b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/geoMod.py index 8c5e93e2..d39b4096 100755 --- a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/geoMod.py +++ b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/geoMod.py @@ -15,9 +15,10 @@ except ImportError: import ESMF +import logging from functools import cached_property, wraps from typing import Any -import logging + import xarray as xr from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.config import ( diff --git a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/parallel.py b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/parallel.py index e0e48891..f0954e56 100755 --- a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/parallel.py +++ b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/parallel.py @@ -1,9 +1,11 @@ +from __future__ import annotations + import atexit -from functools import partial import os -import uuid import signal import sys +from functools import partial +from typing import TYPE_CHECKING import mpi4py import numpy as np @@ -12,9 +14,11 @@ from mpi4py import MPI -from .config import ConfigOptions -from . import err_handler -from . import mpi_utils +if TYPE_CHECKING: + from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.config import ( + ConfigOptions, + ) +from . import err_handler, mpi_utils # If MPI was initialized outside of python, # disable initialization/finalization behavior diff --git a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/regrid.py b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/regrid.py index 427791ce..c9297e05 100755 --- a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/regrid.py +++ b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/core/regrid.py @@ -45,19 +45,20 @@ from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.config import ( ConfigOptions, ) - from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.geoMod import ( - GeoMeta, - ) - from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.suppPrecipMod import ( - supplemental_precip, - ) from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.forcingInputMod import ( InputForcings, ) + from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.geoMod import ( + GeoMeta, + ) from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.parallel import ( MpiConfig, ) + from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.suppPrecipMod import ( + supplemental_precip, + ) import logging + from ..esmf_utils import ( esmf_field_retry, esmf_grid_retry, @@ -3985,7 +3986,7 @@ def regrid_nwm(input_forcings, config_options, wrf_hydro_geo_meta, mpi_config): ) input_forcings.height = None - if mpi_config.rank == 0: + if mpi_config.rank == 0 and config_options.perform_downscaling: pt.log_debug( f"Unable to locate HGT_surface in: {input_forcings.file_in2}. Downscaling will not be available." ) @@ -4282,7 +4283,7 @@ def regrid_nwm_aws(input_forcings, config_options, wrf_hydro_geo_meta, mpi_confi ) input_forcings.height = None - if mpi_config.rank == 0: + if mpi_config.rank == 0 and config_options.perform_downscaling: pt.log_info( f"Unable to locate HGT_surface in: {input_forcings.file_in2}. Downscaling will not be available." ) @@ -4849,7 +4850,7 @@ def regrid_custom_hourly_netcdf( else: input_forcings.height = None - if mpi_config.rank == 0: + if mpi_config.rank == 0 and config_options.perform_downscaling: pt.log_info( f"Unable to locate HGT_surface in: {input_forcings.file_in2}. Downscaling will not be available." ) @@ -7217,7 +7218,7 @@ def regrid_mrms_hourly( id_mrms = None id_mrms_rqi = None try: - pt.log_info("Rrgrid MRMS") + pt.log_info("Rregrid MRMS") if supplemental_precip.file_type != NETCDF: # Unzip MRMS files to temporary locations. @@ -9683,7 +9684,10 @@ def regrid_sbcv2_liquid_water_fraction( def regrid_hourly_nbm( - forcings_or_precip:supplemental_precip|InputForcings, config_options:ConfigOptions, wrf_hydro_geo_meta:GeoMeta, mpi_config:MpiConfig + forcings_or_precip: supplemental_precip | InputForcings, + config_options: ConfigOptions, + wrf_hydro_geo_meta: GeoMeta, + mpi_config: MpiConfig, ): """Regrid hourly NBM precipitation. @@ -9739,7 +9743,7 @@ def regrid_hourly_nbm( cmd = f'$WGRIB2 -match "({"|".join(fields)})" -not "prob" -not "ens" {forcings_or_precip.file_in1} -netcdf {nbm_tmp_nc}' else: # Perform a GRIB dump to NetCDF for the precip data. - time_str=f"{forcings_or_precip.fcst_hour1}-{forcings_or_precip.fcst_hour2} hour acc fcst" + time_str = f"{forcings_or_precip.fcst_hour1}-{forcings_or_precip.fcst_hour2} hour acc fcst" fieldnbm_match1 = f'":APCP:surface:{time_str}:"' fieldnbm_match2 = ( f'"{forcings_or_precip.fcst_hour1}-{forcings_or_precip.fcst_hour2}"' diff --git a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/esmf_utils.py b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/esmf_utils.py index 2076278a..f49b8960 100644 --- a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/esmf_utils.py +++ b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/esmf_utils.py @@ -1,3 +1,6 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any import types import esmpy as ESMF @@ -7,8 +10,9 @@ import shapely from . import retry_utils -from .core.config import ConfigOptions -from .core.parallel import MpiConfig +if TYPE_CHECKING: + from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.config import ConfigOptions + from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.parallel import MpiConfig @retry_utils.retry_w_mpi_context( diff --git a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/model.py b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/model.py index 9fbaa1f4..fec3eb05 100755 --- a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/model.py +++ b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/model.py @@ -1,12 +1,17 @@ +"""NWMv3ForcingEngineModel, to be constructed and managed by inheritors of NWMv3_Forcing_Engine_BMI_model_Base from bmi_model.py.""" + +from __future__ import annotations + +import copy import datetime -import os -from contextlib import contextmanager -from time import time import logging +from contextlib import contextmanager +from functools import partial +from time import perf_counter, time +from typing import TYPE_CHECKING + import numpy as np import pandas as pd -from ewts import Payload as Pld -from ewts import Status as St from ewts.modules import ModuleKey from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core import ( @@ -14,16 +19,12 @@ disaggregateMod, downscale, err_handler, + forcingInputMod, layeringMod, ) -from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.config import ( - ConfigOptions, +from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.consts import ( + MODEL as model_consts, ) -from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.geoMod import ( - GeoMeta, -) -from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.ioMod import OutputObj -from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.parallel import MpiConfig from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.historical_forcing import ( AORCAlaskaProcessor, AORCConusProcessor, @@ -32,6 +33,11 @@ NWMV3OConusProcessor, ) +if TYPE_CHECKING: + from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.bmi_model import ( + NWMv3_Forcing_Engine_BMI_model_Base, + ) + LOG = logging.getLogger("FORCING") MODNM = ModuleKey.FORCING.value @@ -39,20 +45,18 @@ @contextmanager def timing_block(step_str: str): - """Context manager for timing code execution. - - Args: - step_str: Description of the step being timed. + """Context manager for timing code execution. Used by the decorator ``time_function``. + :param str step_str: Description of the step being timed. """ - start = time() + start = perf_counter() yield - end = time() - LOG.debug(f" Execution time for {step_str}: {round(end - start, 2)} seconds") + end = perf_counter() + LOG.debug(msg=f" Execution time for {step_str}: {round(end - start, 2)} seconds") def time_function(func): - """Measure the execution time of a function.""" + """Measure execution time of a function.""" def wrapper(*args, **kwargs): with timing_block(f"Executing {func.__name__}"): @@ -63,752 +67,636 @@ def wrapper(*args, **kwargs): class NWMv3ForcingEngineModel: - """NextGen Forcings Engine BMI model class for NWMv3 forcings.""" + """NextGen Forcings Engine BMI model class for NWMv3 forcings. + + To be constructed and managed by inheritors of NWMv3_Forcing_Engine_BMI_model_Base from bmi_model.py. + """ - def __init__(self): - """Initialize the NWMv3 Forcing Engine Model.""" + def __init__(self, bmi_model: NWMv3_Forcing_Engine_BMI_model_Base): + """Initialize the NWMv3 Forcing Engine model. + + :param bmi_model NWMv3_Forcing_Engine_BMI_model_Base: BMI model instance to initialize. + """ self.source_data_processor = None + self._bmi = bmi_model + # Partials + self.log_info = partial( + err_handler.log_msg, self._bmi._job_meta, self._bmi._mpi_meta, False + ) + self.log_debug = partial( + err_handler.log_msg, self._bmi._job_meta, self._bmi._mpi_meta, True + ) - # TODO: refactor the bmi_model.py file and this to have this type maintain its own state. - # def __init__(self): - # super(ngen_model, self).__init__() - # #self._model = model - - # @dask.delayed - # def aws_obj(files): - # return xr.open_mfdataset(files, engine="zarr", parallel=True, consolidated=True) - - def run( - self, - model: dict, - future_time: float, - config_options: ConfigOptions, - wrf_hydro_geo_meta: GeoMeta, - input_forcing_mod: dict, - supp_pcp_mod: dict, - mpi_config: MpiConfig, - output_obj: OutputObj, - ) -> None: + def check_program_status(self) -> None: + """Call err_handler.check_program_status.""" + err_handler.check_program_status(self._bmi._job_meta, self._bmi._mpi_meta) + + def run(self, future_time: float) -> None: """Execute the full forcings engine BMI pipeline for a given future timestep. - This method updates the `model` state dictionary with atmospheric forcings computed from - available input datasets. It handles initialization, AWS Zarr loading, regridding, temporal - interpolation, bias correction, downscaling, supplemental precipitation processing, and output - population into the model structure. + This method updates the ``self._bmi._values`` state dictionary with atmospheric + forcings computed from available input datasets. It handles initialization, + AWS Zarr loading, regridding, temporal interpolation, bias correction, + downscaling, supplemental precipitation processing, and output population into + the ``self._bmi._values`` structure. + + ``self._bmi._job_meta``, an instance of ``ConfigOptions``, is also updated + in-place, for example for forecast time handling. The following steps are performed: 1. Determine the current forecast and output times based on the future timestamp - and analysis mode (AnA or forecast). + and analysis mode (AnA or forecast). 2. Initialize or reset output grids and step counters. 3. Loop over each input forcing product: - a. Calculate neighboring input files. - b. Load AWS-hosted Zarr datasets if needed. - c. Regrid input forcings to the model grid. - d. Perform temporal interpolation. - e. Apply bias correction and downscaling. - f. Layer final forcings into the output object. + a. Calculate neighboring input files. + b. Load AWS-hosted Zarr datasets if needed. + c. Regrid input forcings to the model grid. + d. Perform temporal interpolation. + e. Apply bias correction and downscaling. + f. Layer final forcings into the output object. 4. Optionally process supplemental precipitation forcings: - a. Regrid and validate. - b. Disaggregate and interpolate. - c. Layer into the final output. + a. Regrid and validate. + b. Disaggregate and interpolate. + c. Layer into the final output. 5. Write output to NetCDF forcing files if requested. - 6. Update the model state dictionary with flattened arrays. + 6. Update the ``self._bmi._values`` state dictionary with flattened arrays. 7. Advance the BMI time index. - :param model: The model state dictionary that will be updated with new forcing data. - :param future_time: The number of seconds into the future to advance the model. - :param config_options: Configuration object containing all model options, flags, and paths. - :param wrf_hydro_geo_meta: Geospatial metadata needed for regridding and interpolation. - :param input_forcing_mod: Dictionary of initialized input forcing modules indexed by forcing key. - :param supp_pcp_mod: Dictionary of supplemental precipitation modules indexed by key. - :param mpi_config: Object containing MPI communication settings such as rank and communicator. - :param output_obj: Output object that stores the generated atmospheric forcing arrays. + :param float future_time: Timestamp, represented as *seconds relative to overall + start time*, to advance to before returning. Since this value is relative + to the overall start time, it is unaware of the actual UTC datetimestamp of + the start. For example, since 1-hour timesteps are typical, the first value + would typically be 3600, the second value 7200, etc. - :raises RuntimeError: If the model fails to initialize or if required arguments are missing. + :raises RuntimeError: If the model fails to initialize or if required arguments + are missing. """ - LOG.debug( - f"{Pld(St.INPROG, msg=f'Starting timestep with future_time={future_time}', modnm=MODNM)}", - ) - ( - future_time, - config_options, - ) = self.determine_forecast( - future_time, - config_options, - ) - ( - config_options, - input_forcing_mod, - mpi_config, - ) = self.adjust_precip( - config_options, - input_forcing_mod, - mpi_config, - ) - ( - config_options, - mpi_config, - ) = self.log_forecast( - config_options, - mpi_config, - ) - ( - future_time, - config_options, - wrf_hydro_geo_meta, - input_forcing_mod, - supp_pcp_mod, - mpi_config, - output_obj, - input_forcings, - ) = self.loop_through_forcing_products( - future_time, - config_options, - wrf_hydro_geo_meta, - input_forcing_mod, - supp_pcp_mod, - mpi_config, - output_obj, - ) - ( - config_options, - wrf_hydro_geo_meta, - supp_pcp_mod, - mpi_config, - output_obj, - ) = self.process_suplemental_precip( - config_options, - wrf_hydro_geo_meta, - supp_pcp_mod, - mpi_config, - output_obj, - input_forcings, - ) - ( - config_options, - wrf_hydro_geo_meta, - mpi_config, - output_obj, - ) = self.write_output( - config_options, - wrf_hydro_geo_meta, - mpi_config, - output_obj, - ) - ( - model, - config_options, - wrf_hydro_geo_meta, - output_obj, - ) = self.update_dict( - model, - config_options, - wrf_hydro_geo_meta, - output_obj, - ) + self.set_cycle_timing_attrs(future_time) + self.set_skip_flags() + self.log_cycle() + input_forcings = self.loop_through_forcing_products(future_time) + self.process_suplemental_precip(input_forcings) + self.write_output() + self.update_bmi_output_dict() ## Update BMI model time index to next iteration - config_options.bmi_time_index += 1 + self._bmi._job_meta.bmi_time_index += 1 @time_function - def determine_forecast( - self, - future_time: float, - config_options: ConfigOptions, - ): - """Determine the forecast for the given future time and configuration.""" + def set_cycle_timing_attrs(self, future_time: float) -> None: + """Determine the forecast for the given future time and configuration. + + :warning: Modifies mutable arguments in-place + """ # Assign the future time to the configuration - config_options.bmi_time = future_time - self.disaggregate_fun = disaggregateMod.disaggregate_factory(config_options) + self._bmi._job_meta.bmi_time = future_time + self.disaggregate_fun = disaggregateMod.disaggregate_factory( + self._bmi._job_meta + ) # Calculate current time stamp based on operational configuration - if config_options.ana_flag: + if self._bmi._job_meta.ana_flag: # If we're in an AnA configuration, then must offset the BMI future # timestamp to account for the "lookback" period being properly iterated # over between 3-28 hour look back time period and operation configuration - - #if config_options.input_forcings[0] in [20, 22]: - # config_options.current_fcst_cycle = ( - # config_options.b_date_proc - # + pd.TimedeltaIndex( - # np.array([future_time - 7200.0], dtype=float), "s" - # )[0] - # ) - # config_options.current_time = ( - # config_options.b_date_proc - # + pd.TimedeltaIndex( - # np.array([future_time - 7200.0], dtype=float), "s" - # )[0] - # ) - # config_options.future_time = future_time - # else: - - # Puerto Rico / Hawaii AnA: 1-hour lookback (based on 6-hourly forecast cycles) - config_options.current_fcst_cycle = ( - config_options.b_date_proc - + pd.TimedeltaIndex( - np.array([future_time - 3600.0], dtype=float), "s" + # TODO confirm these codes, and should they consider all input_forcings not just [0]? + if self._bmi._job_meta.input_forcings[0] in [20, 22]: + # NOTE This appears to be intending to operate on Alaska-only AnA. + delta = pd.TimedeltaIndex( + np.array([future_time - 7200.0], dtype=float), "s" )[0] - ) - config_options.current_time = ( - config_options.b_date_proc - + pd.TimedeltaIndex( + self._bmi._job_meta.current_fcst_cycle = ( + self._bmi._job_meta.b_date_proc + delta + ) + self._bmi._job_meta.current_time = ( + self._bmi._job_meta.b_date_proc + delta + ) + self._bmi._job_meta.future_time = future_time + else: + # NOTE below comment was original, but this appears to be operating on all non-Alaska AnA, not just Puerto Rico / Hawaii AnA. + # Puerto Rico / Hawaii AnA: 1-hour lookback (based on 6-hourly forecast cycles) + delta = pd.TimedeltaIndex( np.array([future_time - 3600.0], dtype=float), "s" )[0] - ) + self._bmi._job_meta.current_fcst_cycle = ( + self._bmi._job_meta.b_date_proc + delta + ) + self._bmi._job_meta.current_time = ( + self._bmi._job_meta.b_date_proc + delta + ) else: # Forecast-only mode — use BMI timestamp as-is - config_options.current_fcst_cycle = config_options.b_date_proc - config_options.current_time = pd.Timestamp( - config_options.b_date_proc + self._bmi._job_meta.current_fcst_cycle = self._bmi._job_meta.b_date_proc + self._bmi._job_meta.current_time = pd.Timestamp( + self._bmi._job_meta.b_date_proc ) + pd.to_timedelta(future_time, unit="s") - LOG.debug( - "NextGen Forcings Engine processing meteorological forcings for BMI timestamp" + self.log_debug( + msg="NextGen Forcings Engine processing meteorological forcings for BMI timestamp" ) - LOG.debug(f"Model.py current time: {config_options.current_time}") - LOG.debug(f"Model.py current fcst cycle: {config_options.current_fcst_cycle}") - - if config_options.first_fcst_cycle is None: - config_options.first_fcst_cycle = config_options.current_fcst_cycle - - return ( - future_time, - config_options, + self.log_debug(msg=f"Model.py current time: {self._bmi._job_meta.current_time}") + self.log_debug( + msg=f"Model.py current fcst cycle: {self._bmi._job_meta.current_fcst_cycle}" ) + if self._bmi._job_meta.first_fcst_cycle is None: + self._bmi._job_meta.first_fcst_cycle = ( + self._bmi._job_meta.current_fcst_cycle + ) + @time_function - def adjust_precip( - self, - config_options: ConfigOptions, - input_forcing_mod: dict, - mpi_config: MpiConfig, - ): + def set_skip_flags(self) -> None: """Adjust precipitation for the given forecast cycle.""" - if not config_options.precip_only_flag: + if not self._bmi._job_meta.precip_only_flag: # reset skips if present - for force_key in config_options.input_forcings: - input_forcing_mod[force_key].skip = False - - err_handler.check_program_status(config_options, mpi_config) - return ( - config_options, - input_forcing_mod, - mpi_config, - ) + for force_key in self._bmi._job_meta.input_forcings: + self._bmi._input_forcing_mod[force_key].skip = False + + self.check_program_status() @time_function - def log_forecast( - self, - config_options: ConfigOptions, - mpi_config: MpiConfig, - ): + def log_cycle(self) -> None: """Log information about the current forecast cycle.""" - # Log information about this forecast cycle - if mpi_config.rank == 0: - config_options.statusMsg = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" - err_handler.log_msg(config_options, mpi_config, True) - config_options.statusMsg = ( - "Processing Forecast Cycle: " - + config_options.current_fcst_cycle.strftime("%Y-%m-%d %H:%M") + if self._bmi._mpi_meta.rank == 0: + self.log_debug(msg="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") + self.log_debug( + msg=f"Processing Forecast Cycle: {self._bmi._job_meta.current_fcst_cycle.strftime('%Y-%m-%d %H:%M')}" ) - err_handler.log_msg(config_options, mpi_config, True) - config_options.statusMsg = ( - "Forecast Cycle Length is: " - + str(config_options.cycle_length_minutes) - + " minutes" + self.log_debug( + msg=f"Forecast Cycle Length is: {self._bmi._job_meta.cycle_length_minutes!s} minutes" ) - err_handler.log_msg(config_options, mpi_config, True) - # mpi_config.comm.barrier() - - return ( - config_options, - mpi_config, - ) + # self._bmi._mpi_meta.comm.barrier() @time_function def loop_through_forcing_products( - self, - future_time: float, - config_options: ConfigOptions, - wrf_hydro_geo_meta: GeoMeta, - input_forcing_mod: dict, - supp_pcp_mod: dict, - mpi_config: MpiConfig, - output_obj: OutputObj, - ): - """Loop through each forcing product and process it for the current forecast cycle.""" - # Loop through each output timestep. Perform the following functions: - # 1.) Calculate all necessary input files per user options. - # 2.) Read in input forcings from GRIB/NetCDF files. - # 3.) Regrid the forcings, and temporally interpolate. - # 4.) Downscale. - # 5.) Layer, and output as necessary. - ana_factor = 1 if config_options.ana_flag is False else 0 - show_message = True - if not config_options.precip_only_flag: - if config_options.grid_type == "gridded": + self, future_time: float + ) -> forcingInputMod.InputForcingsHydrofabric | None: + """Loop through each forcing product and process it for the current forecast cycle. + + Loop through each output timestep and perform the following steps: + + 1. Calculate all necessary input files per user options. + 2. Read input forcings from GRIB/NetCDF files. + 3. Regrid the forcings and perform temporal interpolation. + 4. Downscale. + 5. Layer and write output as necessary. + + :param float future_time: See description in ``self.run``. + :returns: Processed input forcings for the current timestep. + :rtype: forcingInputMod.InputForcings | None + """ + ana_factor = 1 if self._bmi._job_meta.ana_flag is False else 0 + if not self._bmi._job_meta.precip_only_flag: + if self._bmi._job_meta.grid_type == "gridded": # Reset out final grids to missing values. - output_obj.output_local[:, :, :] = config_options.globalNdv - elif config_options.grid_type == "unstructured": + self._bmi._output_obj.output_local[:, :, :] = ( + self._bmi._job_meta.globalNdv + ) + elif self._bmi._job_meta.grid_type == "unstructured": # Reset out final grids to missing values. - output_obj.output_local[:, :] = config_options.globalNdv - output_obj.output_local_elem[:, :] = config_options.globalNdv - elif config_options.grid_type == "hydrofabric": + self._bmi._output_obj.output_local[:, :] = self._bmi._job_meta.globalNdv + self._bmi._output_obj.output_local_elem[:, :] = ( + self._bmi._job_meta.globalNdv + ) + elif self._bmi._job_meta.grid_type == "hydrofabric": # Reset out final grids to missing values. - output_obj.output_local[:, :] = config_options.globalNdv + self._bmi._output_obj.output_local[:, :] = self._bmi._job_meta.globalNdv + else: + raise ValueError( + f"Unexpected grid_type: {repr(self._bmi._job_meta.grid_type)}" + ) # Increment or initialize output step count - if config_options.current_output_step is None: - config_options.current_output_step = 1 + if self._bmi._job_meta.current_output_step is None: + self._bmi._job_meta.current_output_step = 1 else: - config_options.current_output_step += 1 + self._bmi._job_meta.current_output_step += 1 # Optional sub-output timestamp - if config_options.sub_output_hour is not None: - # TODO This is not used - subOutDate = config_options.first_fcst_cycle + datetime.timedelta( - hours=config_options.sub_output_hour - ) + # if self._bmi._job_meta.sub_output_hour is not None: + # raise NotImplementedError( + # f"sub_output_hour (config SubOutputHour) is {repr(self._bmi._job_meta.sub_output_hour)} (not None) but is not used." + # ) + # # TODO This is not used. The raise not implemented error causes a fail on medium range blen due to the sub_output_hour being + # specified in the config file. Testing was performed and not specifying sub_output_hour produces the same results for medium range blend + # as of 7/13/2026. Not sure what this was intended to do but it is not used/effective at this time. Commenting it out to ensure medium range blend completes + # and it is retained in case the intent is realized and it should be resurrected. + + # subOutDate = self._bmi._job_meta.first_fcst_cycle + datetime.timedelta( + # hours=self._bmi._job_meta.sub_output_hour + # ) # Compute the output timestamp for this step - if config_options.ana_flag: - output_obj.outDate = ( - config_options.current_fcst_cycle - + datetime.timedelta(seconds=config_options.output_freq * 60) + if self._bmi._job_meta.ana_flag: + self._bmi._output_obj.outDate = ( + self._bmi._job_meta.current_fcst_cycle + + datetime.timedelta(seconds=self._bmi._job_meta.output_freq * 60) ) else: - output_obj.outDate = ( - config_options.current_fcst_cycle + self._bmi._output_obj.outDate = ( + self._bmi._job_meta.current_fcst_cycle + datetime.timedelta(seconds=future_time) ) - config_options.current_output_date = output_obj.outDate + self._bmi._job_meta.current_output_date = self._bmi._output_obj.outDate # Adjust file_date for AnA if needed file_date = ( - output_obj.outDate - - datetime.timedelta(seconds=config_options.output_freq * 60) - if config_options.ana_flag - else output_obj.outDate + self._bmi._output_obj.outDate + - datetime.timedelta(seconds=self._bmi._job_meta.output_freq * 60) + if self._bmi._job_meta.ana_flag + else self._bmi._output_obj.outDate ) # Compute previous output date (used for downscaling logic) - if config_options.current_output_step == ana_factor: - config_options.prev_output_date = config_options.current_output_date + if self._bmi._job_meta.current_output_step == ana_factor: + self._bmi._job_meta.prev_output_date = ( + self._bmi._job_meta.current_output_date + ) else: - config_options.prev_output_date = ( - config_options.current_output_date + self._bmi._job_meta.prev_output_date = ( + self._bmi._job_meta.current_output_date - datetime.timedelta(seconds=future_time) ) # Print message on log file indicating the timestamp # we are currently processing for forcings - if mpi_config.rank == 0 and show_message: - config_options.statusMsg = "=========================================" - err_handler.log_msg(config_options, mpi_config, True) - config_options.statusMsg = f"Processing for output timestep: {file_date.strftime('%Y-%m-%d %H:%M')}" - err_handler.log_msg(config_options, mpi_config, True) - - config_options.currentForceNum = 0 - config_options.currentCustomForceNum = 0 - LOG.debug(f"config_options.input_forcings: {config_options.input_forcings}") + if self._bmi._mpi_meta.rank == 0: + self.log_debug(msg="=========================================") + self.log_debug( + msg=f"Processing for output timestep: {file_date.strftime('%Y-%m-%d %H:%M')}" + ) + + self._bmi._job_meta.currentForceNum = 0 + self._bmi._job_meta.currentCustomForceNum = 0 + self.log_debug( + msg=f"config_options.input_forcings: {self._bmi._job_meta.input_forcings}" + ) # Loop over each of the input forcings specified. - LOG.debug( - f"Model.py forcing loop: {len(config_options.input_forcings)} forcings configured: {config_options.input_forcings}" + self.log_debug( + msg=f"Model.py forcing loop: {len(self._bmi._job_meta.input_forcings)} forcings configured: {self._bmi._job_meta.input_forcings}" ) - for force_key in config_options.input_forcings: - LOG.debug(f"force_key: {force_key}") - LOG.debug(f"config_options.aws: {config_options.aws}") + for force_key in self._bmi._job_meta.input_forcings: + self.log_debug(msg=f"force_key: {force_key}") + self.log_debug(msg=f"config_options.aws: {self._bmi._job_meta.aws}") # Pass these methods for AORC data is ERA5-Interim blend is requested # so we can finish filling in the missing gaps if ( force_key == 23 - and 12 in config_options.input_forcings - and 21 in config_options.input_forcings + and 12 in self._bmi._job_meta.input_forcings + and 21 in self._bmi._job_meta.input_forcings ): - input_forcings = input_forcing_mod[force_key] + input_forcings = self._bmi._input_forcing_mod[force_key] # These are not used # AORC_mask = input_forcings.regridded_mask_AORC # AORC_elem_mask = input_forcings.regridded_mask_elem_AORC else: - input_forcings = input_forcing_mod[force_key] + input_forcings = self._bmi._input_forcing_mod[force_key] input_forcings.calc_neighbor_files( - config_options, output_obj.outDate, mpi_config + self._bmi._job_meta, + self._bmi._output_obj.outDate, + self._bmi._mpi_meta, ) - if force_key in [12, 21, 27]: - if config_options.aws is None: - # Calculate the previous and next input cycle files from the inputs. - input_forcings.calc_neighbor_files( - config_options, output_obj.outDate, mpi_config - ) - err_handler.check_program_status(config_options, mpi_config) - else: - # Flag to indicate the AWS .zarr AORC method - if force_key == 12: - if self.source_data_processor is None: - self.source_data_processor = AORCConusProcessor( - config_options, mpi_config, wrf_hydro_geo_meta - ) - elif force_key == 21: - if self.source_data_processor is None: - self.source_data_processor = AORCAlaskaProcessor( - config_options, mpi_config, wrf_hydro_geo_meta - ) - - # Flag to indicate the AWS .zarr NWMv3 Forcing file method - elif force_key == 27: - if self.source_data_processor is None: - if config_options.nwm_domain == "CONUS": - self.source_data_processor = NWMV3ConusProcessor( - config_options, mpi_config, wrf_hydro_geo_meta - ) - elif config_options.nwm_domain in [ - "Hawaii", - "PR", - ]: - self.source_data_processor = NWMV3OConusProcessor( - config_options, mpi_config, wrf_hydro_geo_meta - ) - elif config_options.nwm_domain == "Alaska": - self.source_data_processor = NWMV3AlaskaProcessor( - config_options, mpi_config, wrf_hydro_geo_meta - ) - else: - raise ValueError( - f"Unsupported domain type ({config_options.nwm_domain} for forcing type: {force_key} )" - ) - - config_options.aws_obj = ( - self.source_data_processor.process_historical_data( - config_options.current_time - ) - ) + # Handle AORC and NWM force keys + self.__handle_aorc_and_nwm_force_keys(input_forcings, force_key) # If skipping this forcing, continue early + # NOTE this is used by the esmf regrid pytests, to halt the loop before "manually" calling a particular regrid function. if input_forcings.skip is True: - LOG.debug(f"Breaking loop for force_key {force_key}") + self.log_debug(msg=f"Breaking loop for force_key {force_key}") break + # Regrid forcings. input_forcings.regrid_inputs( - config_options, wrf_hydro_geo_meta, mpi_config + self._bmi._job_meta, self._bmi.geo_meta, self._bmi._mpi_meta ) - err_handler.check_program_status(config_options, mpi_config) + self.check_program_status() # Run check on regridded fields for reasonable values that are not missing values. err_handler.check_forcing_bounds( - config_options, input_forcings, mpi_config + self._bmi._job_meta, input_forcings, self._bmi._mpi_meta ) - err_handler.check_program_status(config_options, mpi_config) + self.check_program_status() # If we are restarting a forecast cycle, re-calculate the neighboring files, and regrid the # next set of forcings as the previous step just regridded the previous forcing. - if input_forcings.rstFlag == 1: - if ( - input_forcings.regridded_forcings1 is not None - and input_forcings.regridded_forcings2 is not None - ): - # Set the forcings back to reflect we just regridded the previous set of inputs, not the next. - if config_options.grid_type == "gridded": - input_forcings.regridded_forcings1[:, :, :] = ( - input_forcings.regridded_forcings2[:, :, :] - ) - elif config_options.grid_type == "unstructured": - input_forcings.regridded_forcings1[:, :] = ( - input_forcings.regridded_forcings2[:, :] - ) - input_forcings.regridded_forcings1_elem[:, :] = ( - input_forcings.regridded_forcings2_elem[:, :] - ) - elif config_options.grid_type == "hydrofabric": - input_forcings.regridded_forcings1[:, :] = ( - input_forcings.regridded_forcings2[:, :] - ) - # Re-calculate the neighbor files. - input_forcings.calc_neighbor_files( - config_options, output_obj.outDate, mpi_config - ) - err_handler.check_program_status(config_options, mpi_config) - - # Regrid the forcings for the end of the window. - input_forcings.regrid_inputs( - config_options, wrf_hydro_geo_meta, mpi_config - ) - err_handler.check_program_status(config_options, mpi_config) - - input_forcings.rstFlag = 0 + self.__use_rstFlag(input_forcings) # Run temporal interpolation on the grids. - input_forcings.temporal_interpolate_inputs(config_options, mpi_config) - err_handler.check_program_status(config_options, mpi_config) + input_forcings.temporal_interpolate_inputs( + self._bmi._job_meta, self._bmi._mpi_meta + ) + self.check_program_status() # Run bias correction. bias_correction.run_bias_correction( - input_forcings, config_options, wrf_hydro_geo_meta, mpi_config + input_forcings, + self._bmi._job_meta, + self._bmi.geo_meta, + self._bmi._mpi_meta, ) - err_handler.check_program_status(config_options, mpi_config) + self.check_program_status() # Run downscaling on grids for this output timestep. downscale.run_downscaling( - input_forcings, config_options, wrf_hydro_geo_meta, mpi_config + input_forcings, + self._bmi._job_meta, + self._bmi.geo_meta, + self._bmi._mpi_meta, ) - err_handler.check_program_status(config_options, mpi_config) + self.check_program_status() # Layer in forcings from this product. layeringMod.layer_final_forcings( - output_obj, input_forcings, config_options, mpi_config + self._bmi._output_obj, + input_forcings, + self._bmi._job_meta, + self._bmi._mpi_meta, ) - err_handler.check_program_status(config_options, mpi_config) + self.check_program_status() - config_options.currentForceNum += 1 + self._bmi._job_meta.currentForceNum += 1 + # NOTE currentCustomForceNum does not appear to be used. if force_key == 10: - config_options.currentCustomForceNum += 1 + self._bmi._job_meta.currentCustomForceNum += 1 - LOG.debug(f"End of loop for force_key {force_key}") + self.log_debug(msg=f"End of loop for force_key {force_key}") # Process supplemental precipitation if we specified in the configuration file. - if config_options.number_supp_pcp > 0: - for supp_pcp_key in config_options.supp_precip_forcings: + if self._bmi._job_meta.number_supp_pcp > 0: + for supp_pcp_key in self._bmi._job_meta.supp_precip_forcings: if supp_pcp_key != 13: - # Like with input forcings, calculate the neighboring files to use. - supp_pcp_mod[supp_pcp_key].calc_neighbor_files( - config_options, output_obj.outDate, mpi_config - ) - err_handler.check_program_status(config_options, mpi_config) - - # Regrid the supplemental precipitation. - supp_pcp_mod[supp_pcp_key].regrid_inputs( - config_options, wrf_hydro_geo_meta, mpi_config - ) - err_handler.check_program_status(config_options, mpi_config) - - if ( - supp_pcp_mod[supp_pcp_key].regridded_precip1 is not None - and supp_pcp_mod[supp_pcp_key].regridded_precip2 is not None - ): - # Run check on regridded fields for reasonable values that are not missing values. - err_handler.check_supp_pcp_bounds( - config_options, - supp_pcp_mod[supp_pcp_key], - mpi_config, - wrf_hydro_geo_meta, - ) - err_handler.check_program_status(config_options, mpi_config) - - # TODO input_forcings has not yet been initialized, so this is a bug waiting to happen - self.disaggregate_fun( - input_forcings, - supp_pcp_mod[supp_pcp_key], - config_options, - mpi_config, - ) - err_handler.check_program_status(config_options, mpi_config) - - # Run temporal interpolation on the grids. - supp_pcp_mod[supp_pcp_key].temporal_interpolate_inputs( - config_options, mpi_config - ) - err_handler.check_program_status(config_options, mpi_config) - - # Layer in the supplemental precipitation into the current output object. - layeringMod.layer_supplemental_forcing( - output_obj, - supp_pcp_mod[supp_pcp_key], - config_options, - mpi_config, - ) - err_handler.check_program_status(config_options, mpi_config) + # Below comment copied from earlier code, the comment had been just above the call to ``disaggregate_fun``. + # TODO input_forcings has not yet been initialized, so this is a bug waiting to happen + self.__process_supp_precip_key(input_forcings, supp_pcp_key) # Call the output routines # adjust date for AnA if necessary - if config_options.ana_flag: - output_obj.outDate = file_date + if self._bmi._job_meta.ana_flag: + self._bmi._output_obj.outDate = file_date ################ Commenting this out to bypass NWM forcing file output functionality ######### - # output_obj.output_final_ldasin(config_options, wrf_hydro_geo_meta, mpi_config) - # err_handler.check_program_status(config_options, mpi_config) + # self._bmi._output_obj.output_final_ldasin(self._bmi._job_meta, self._bmi.geo_meta, self._bmi._mpi_meta) + # self.check_program_status() ############################################################################################## + else: + input_forcings = None + + return input_forcings + + def __handle_aorc_and_nwm_force_keys( + self, input_forcings: forcingInputMod.InputForcings, force_key: int + ) -> None: + """During ``loop_through_forcing_products``, handle the case where the force key is AORC or NWM. + + This code block was cut and pasted from the method ``loop_through_forcing_products`` during refactor. + + :param input_forcings forcingInputMod.InputForcings: Input forcings object to be modified. + :param int force_key: Identifier for the forcing type. + + :warning: Modifies mutable arguments in-place. + """ + proc_args = (self._bmi._job_meta, self._bmi._mpi_meta, self._bmi.geo_meta) + + if force_key in [12, 21, 27]: + if self._bmi._job_meta.aws is None: + # Calculate the previous and next input cycle files from the inputs. + input_forcings.calc_neighbor_files( + self._bmi._job_meta, + self._bmi._output_obj.outDate, + self._bmi._mpi_meta, + ) + self.check_program_status() + else: + if len(self._bmi._job_meta.input_forcings) != 1: + raise ValueError( + f"Expected to have 1 forcing key, but have {len(self._bmi._job_meta.input_forcings)}: {list(self._bmi._job_meta.input_forcings)}" + ) + if self.source_data_processor is None: + # Flag to indicate the AWS .zarr AORC method + if force_key == 12: + proc_cls = AORCConusProcessor + elif force_key == 21: + proc_cls = AORCAlaskaProcessor + # Flag to indicate the AWS .zarr NWMv3 Forcing file method + elif force_key == 27: + if self._bmi._job_meta.nwm_domain == "CONUS": + proc_cls = NWMV3ConusProcessor + elif self._bmi._job_meta.nwm_domain in [ + "Hawaii", + "PR", + ]: + proc_cls = NWMV3OConusProcessor + elif self._bmi._job_meta.nwm_domain == "Alaska": + proc_cls = NWMV3AlaskaProcessor + else: + raise ValueError( + f"Unsupported domain type ({self._bmi._job_meta.nwm_domain} for forcing type: {force_key} )" + ) + else: + raise ValueError(f"Unexpected force_key: {force_key}") + self.source_data_processor = proc_cls(*proc_args) + + self._bmi._job_meta.aws_obj = ( + self.source_data_processor.process_historical_data( + self._bmi._job_meta.current_time + ) + ) - return ( - future_time, - config_options, - wrf_hydro_geo_meta, - input_forcing_mod, - supp_pcp_mod, - mpi_config, - output_obj, - input_forcings, + def __process_supp_precip_key( + self, input_forcings: forcingInputMod.InputForcings, supp_pcp_key: int + ) -> None: + """Process supplemental precipitation for a single supplemental precipitation key. + + This code block was cut and pasted from the methods + ``loop_through_forcing_products`` and ``process_suplemental_precip`` during refactor. + + :param input_forcings forcingInputMod.InputForcings: Input forcings object to be modified. + :param int supp_pcp_key: Identifier for the supplemental precipitation forcing. + + :warning: Modifies mutable arguments in-place. + """ + # Like with input forcings, calculate the neighboring files to use. + self._bmi._supp_pcp_mod[supp_pcp_key].calc_neighbor_files( + self._bmi._job_meta, + self._bmi._output_obj.outDate, + self._bmi._mpi_meta, ) + self.check_program_status() + + # Regrid the supplemental precipitation. + self._bmi._supp_pcp_mod[supp_pcp_key].regrid_inputs( + self._bmi._job_meta, self._bmi.geo_meta, self._bmi._mpi_meta + ) + self.check_program_status() + + if ( + self._bmi._supp_pcp_mod[supp_pcp_key].regridded_precip1 is not None + and self._bmi._supp_pcp_mod[supp_pcp_key].regridded_precip2 is not None + ): + # Run check on regridded fields for reasonable values that are not missing values. + err_handler.check_supp_pcp_bounds( + self._bmi._job_meta, + self._bmi._supp_pcp_mod[supp_pcp_key], + self._bmi._mpi_meta, + self._bmi.geo_meta, + ) + self.check_program_status() + + self.disaggregate_fun( + input_forcings, + self._bmi._supp_pcp_mod[supp_pcp_key], + self._bmi._job_meta, + self._bmi._mpi_meta, + ) + self.check_program_status() + + # Run temporal interpolation on the grids. + self._bmi._supp_pcp_mod[supp_pcp_key].temporal_interpolate_inputs( + self._bmi._job_meta, self._bmi._mpi_meta + ) + self.check_program_status() + + # Layer in the supplemental precipitation into the current output object. + layeringMod.layer_supplemental_forcing( + self._bmi._output_obj, + self._bmi._supp_pcp_mod[supp_pcp_key], + self._bmi._job_meta, + self._bmi._mpi_meta, + ) + self.check_program_status() + + def __use_rstFlag(self, input_forcings: forcingInputMod.InputForcings) -> None: + """If restarting a forecast cycle, re-calculate neighboring files and regrid the next set of forcings, as the previous step regridded the prior forcing. + + This code block was cut and pasted from the method + ``loop_through_forcing_products`` during refactor. + + :param input_forcings forcingInputMod.InputForcings: Input forcings object to be modified. + + :warning: Modifies mutable arguments in-place. + """ + if input_forcings.rstFlag == 1: + if ( + input_forcings.regridded_forcings1 is not None + and input_forcings.regridded_forcings2 is not None + ): + # Set the forcings back to reflect we just regridded the previous set of inputs, not the next. + if self._bmi._job_meta.grid_type == "gridded": + input_forcings.regridded_forcings1[:, :, :] = ( + input_forcings.regridded_forcings2[:, :, :] + ) + elif self._bmi._job_meta.grid_type == "unstructured": + input_forcings.regridded_forcings1[:, :] = ( + input_forcings.regridded_forcings2[:, :] + ) + input_forcings.regridded_forcings1_elem[:, :] = ( + input_forcings.regridded_forcings2_elem[:, :] + ) + elif self._bmi._job_meta.grid_type == "hydrofabric": + input_forcings.regridded_forcings1[:, :] = ( + input_forcings.regridded_forcings2[:, :] + ) + else: + raise ValueError( + f"Unexpected grid_type: {repr(self._bmi._job_meta.grid_type)}" + ) + # Re-calculate the neighbor files. + input_forcings.calc_neighbor_files( + self._bmi._job_meta, + self._bmi._output_obj.outDate, + self._bmi._mpi_meta, + ) + self.check_program_status() + + # Regrid the forcings for the end of the window. + input_forcings.regrid_inputs( + self._bmi._job_meta, self._bmi.geo_meta, self._bmi._mpi_meta + ) + self.check_program_status() + + input_forcings.rstFlag = 0 @time_function def process_suplemental_precip( - self, - config_options: ConfigOptions, - wrf_hydro_geo_meta: GeoMeta, - supp_pcp_mod: dict, - mpi_config: MpiConfig, - output_obj: OutputObj, - input_forcings: dict, - ): - """Process supplemental precipitation for the current forecast cycle.""" - if config_options.customSuppPcpFreq is not None: - # Process supplemental precipitation if we specified in the configuration file. - if config_options.number_supp_pcp > 0: - for supp_pcp_key in config_options.supp_precip_forcings: - if supp_pcp_key == 14: - # Like with input forcings, calculate the neighboring files to use. - supp_pcp_mod[supp_pcp_key].calc_neighbor_files( - config_options, output_obj.outDate, mpi_config - ) - err_handler.check_program_status(config_options, mpi_config) - - # Regrid the supplemental precipitation. - supp_pcp_mod[supp_pcp_key].regrid_inputs( - config_options, wrf_hydro_geo_meta, mpi_config - ) - err_handler.check_program_status(config_options, mpi_config) - - if ( - supp_pcp_mod[supp_pcp_key].regridded_precip1 is not None - and supp_pcp_mod[supp_pcp_key].regridded_precip2 is not None - ): - # Run check on regridded fields for reasonable values that are not missing values. - err_handler.check_supp_pcp_bounds( - config_options, - supp_pcp_mod[supp_pcp_key], - mpi_config, - wrf_hydro_geo_meta, - ) - err_handler.check_program_status(config_options, mpi_config) + self, input_forcings: forcingInputMod.InputForcings + ) -> None: + """Process supplemental precipitation for the current forecast cycle. - self.disaggregate_fun( - input_forcings, - supp_pcp_mod[supp_pcp_key], - config_options, - mpi_config, - ) - err_handler.check_program_status(config_options, mpi_config) + :param input_forcings forcingInputMod.InputForcings: Input forcings object to be modified. - # Run temporal interpolation on the grids. - supp_pcp_mod[supp_pcp_key].temporal_interpolate_inputs( - config_options, mpi_config - ) - err_handler.check_program_status(config_options, mpi_config) - - # Layer in the supplemental precipitation into the current output object. - layeringMod.layer_supplemental_forcing( - output_obj, - supp_pcp_mod[supp_pcp_key], - config_options, - mpi_config, - ) - err_handler.check_program_status(config_options, mpi_config) - - return ( - config_options, - wrf_hydro_geo_meta, - supp_pcp_mod, - mpi_config, - output_obj, - ) + :warning: Modifies mutable arguments in-place. + """ + if self._bmi._job_meta.customSuppPcpFreq is not None: + # Process supplemental precipitation if we specified in the configuration file. + if self._bmi._job_meta.number_supp_pcp > 0: + for supp_pcp_key in self._bmi._job_meta.supp_precip_forcings: + if supp_pcp_key == 14: + self.__process_supp_precip_key(input_forcings, supp_pcp_key) @time_function - def write_output( - self, - config_options: ConfigOptions, - wrf_hydro_geo_meta: GeoMeta, - mpi_config: MpiConfig, - output_obj: OutputObj, - ): - """Write the output for the current forecast cycle.""" - # If user requests output for given domain, then call - # the I/O module to update opened netcdf file with forcing fields + def write_output(self) -> None: + """Write the output for the current forecast cycle. + + If user requests output for given domain, then call + the I/O module to update opened netcdf file with forcing fields. + """ if ( - config_options.forcing_output == 1 - or config_options.grid_type == "hydrofabric" + self._bmi._job_meta.forcing_output == 1 + or self._bmi._job_meta.grid_type == "hydrofabric" ): - output_obj.gather_global_outputs( - config_options, wrf_hydro_geo_meta, mpi_config + self._bmi._output_obj.gather_global_outputs( + self._bmi._job_meta, self._bmi.geo_meta, self._bmi._mpi_meta ) - return ( - config_options, - wrf_hydro_geo_meta, - mpi_config, - output_obj, - ) - - """##################Step 6: flatten and update dict##########################################################################""" @time_function - def update_dict( - self, - model: dict, - config_options: ConfigOptions, - wrf_hydro_geo_meta: GeoMeta, - output_obj: OutputObj, - ): - """Flatten the Forcings Engine output object and update the BMI dictionary.""" - # Now loop through Forcings Engine output object - # and flatten the 2D forcing array and append to - # the BMI object to advertise to BMIinterface - # 0.) U-Wind (m/s) - # 1.) V-Wind (m/s) - # 2.) Surface incoming longwave radiation flux (W/m^2) - # 3.) Precipitation rate (mm/s) - # 4.) 2-meter temperature (K) - # 5.) 2-meter specific humidity (kg/kg) - # 6.) Surface pressure (Pa) - # 7.) Surface incoming shortwave radiation flux (W/m^2) - # 8.) Liquid Precipitation Fraction (%), Only available in certain operational configurations - - if config_options.include_lqfrac == 1: - variables = [ - "U2D", - "V2D", - "LWDOWN", - "RAINRATE", - "T2D", - "Q2D", - "PSFC", - "SWDOWN", - "LQFRAC", - ] - else: - variables = [ - "U2D", - "V2D", - "LWDOWN", - "RAINRATE", - "T2D", - "Q2D", - "PSFC", - "SWDOWN", - ] - if config_options.grid_type == "gridded": + def update_bmi_output_dict(self) -> None: + """Flatten the Forcings Engine output object and update the BMI dictionary. + + Loop through the Forcings Engine output object, flatten the 2D forcing arrays, + and append them to the BMI object for advertisement through the BMI interface. + + The flattened variables are ordered as follows: + + 0. U-wind (m/s) + 1. V-wind (m/s) + 2. Surface incoming longwave radiation flux (W/m²) + 3. Precipitation rate (mm/s) + 4. 2-meter air temperature (K) + 5. 2-meter specific humidity (kg/kg) + 6. Surface pressure (Pa) + 7. Surface incoming shortwave radiation flux (W/m²) + 8. Liquid precipitation fraction (%), available only in certain operational configurations + """ + variables = copy.deepcopy(model_consts["update_dict_base_vars"]) + if self._bmi._job_meta.include_lqfrac == 1: + variables.append(model_consts["update_dict_var_include_lqfraq"]) + + if self._bmi._job_meta.grid_type == "gridded": for count, variable in enumerate(variables): - model[variable + "_ELEMENT"] = output_obj.output_local[ - count, :, : - ].flatten() - elif config_options.grid_type == "unstructured": + self._bmi._values[f"{variable}_ELEMENT"] = ( + self._bmi._output_obj.output_local[count, :, :].flatten() + ) + elif self._bmi._job_meta.grid_type == "unstructured": for count, variable in enumerate(variables): - model[variable + "_ELEMENT"] = output_obj.output_local_elem[ - count, : - ].flatten() - model[variable + "_NODE"] = output_obj.output_local[count, :].flatten() - elif config_options.grid_type == "hydrofabric": + self._bmi._values[f"{variable}_ELEMENT"] = ( + self._bmi._output_obj.output_local_elem[count, :].flatten() + ) + self._bmi._values[f"{variable}_NODE"] = ( + self._bmi._output_obj.output_local[count, :].flatten() + ) + elif self._bmi._job_meta.grid_type == "hydrofabric": for count, variable in enumerate(variables): - model[variable + "_ELEMENT"] = output_obj.output_global[ - count, : - ].flatten() - - return ( - model, - config_options, - wrf_hydro_geo_meta, - output_obj, - ) + self._bmi._values[f"{variable}_ELEMENT"] = ( + self._bmi._output_obj.output_global[count, :].flatten() + ) + self._bmi._values["CAT-ID"] = self._bmi.geo_meta.element_ids_global + else: + raise ValueError( + f"Unexpected grid_type: {repr(self._bmi._job_meta.grid_type)}" + ) diff --git a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/os_utils.py b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/os_utils.py index 3d823c60..7853da24 100644 --- a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/os_utils.py +++ b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/os_utils.py @@ -1,9 +1,19 @@ -from . import retry_utils +from __future__ import annotations + import traceback import types import typing -from .core.parallel import MpiConfig -from .core.config import ConfigOptions +from typing import TYPE_CHECKING + +from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine import retry_utils + +if TYPE_CHECKING: + from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.config import ( + ConfigOptions, + ) + from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.parallel import ( + MpiConfig, + ) import os diff --git a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/retry_utils.py b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/retry_utils.py index 779dd7dd..81594156 100644 --- a/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/retry_utils.py +++ b/NextGen_Forcings_Engine_BMI/NextGen_Forcings_Engine/retry_utils.py @@ -1,10 +1,18 @@ +from __future__ import annotations + import functools import time import traceback import types +from typing import TYPE_CHECKING, Any -from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.parallel import MpiConfig -from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.config import ConfigOptions +if TYPE_CHECKING: + from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.config import ( + ConfigOptions, + ) + from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.parallel import ( + MpiConfig, + ) def retry_w_mpi_context( @@ -40,6 +48,13 @@ def wrapper( *args, **kwargs, ): + from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.config import ( + ConfigOptions, + ) + from NextGen_Forcings_Engine_BMI.NextGen_Forcings_Engine.core.parallel import ( + MpiConfig, + ) + if not isinstance(mpi_config, MpiConfig): raise TypeError( f"Expected type {MpiConfig} for mpi_config, got: {type(mpi_config)}" diff --git a/NextGen_Forcings_Engine_BMI/run_bmi_model.py b/NextGen_Forcings_Engine_BMI/run_bmi_model.py index 70c56d52..553b6cf6 100755 --- a/NextGen_Forcings_Engine_BMI/run_bmi_model.py +++ b/NextGen_Forcings_Engine_BMI/run_bmi_model.py @@ -343,17 +343,11 @@ def run_bmi( config = parse_config(yaml.safe_load(fp)) print("Creating an instance of the BMI model object") - model = BMIMODEL[config.get("GRID_TYPE")]() - - # IMPORTANT: We are not calling initialize() directly here. - # Instead, we call initialize_with_params(), which handles - # the initialization process and internally calls initialize(). - model.initialize_with_params( - cfg_path, - b_date=b_date, - geogrid=geogrid, - output_path=str(output_path) if output_path else None, + model = BMIMODEL[config.get("GRID_TYPE")]( + b_date, geogrid, output_path=str(output_path) if output_path else None ) + model.initialize(cfg_path) + ngen_datetimes, start_time, end_time = get_date_times(start_time, end_time) num_iterations = len(ngen_datetimes) print_init(model, num_iterations) diff --git a/tests/test_utils.py b/tests/test_utils.py index aaeaee78..5aab1f0d 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -557,64 +557,20 @@ def pre_regrid(self) -> None: f"In pre_regrid, expected state to be either None or 'post_ran' but got {repr(self._state)}. The test is set up incorrectly." ) - config_options = self.config_options - mpi_config = self.mpi_config - geo_meta = self.geo_meta - supp_pcp_mod = self.bmi_model._supp_pcp_mod - output_obj = self.bmi_model._output_obj - input_forcing_mod = self.bmi_model._input_forcing_mod - future_time = ( self.bmi_model._values["current_model_time"] + self.bmi_model._values["time_step_size"] ) model = self.bmi_model._model - ### NOTE with the exception of setting the skip flag, the below - ### block is copied verbatim from NWMv3ForcingEngineModel.run() - ( - future_time, - config_options, - ) = model.determine_forecast( - future_time, - config_options, - ) - ( - config_options, - input_forcing_mod, - mpi_config, - ) = model.adjust_precip( - config_options, - input_forcing_mod, - mpi_config, - ) - ( - config_options, - mpi_config, - ) = model.log_forecast( - config_options, - mpi_config, - ) + # NOTE this should mimic NWMv3ForcingEngineModel.run() + # with the exception of externally setting the skip flags within this class. + model.set_cycle_timing_attrs(future_time) + model.set_skip_flags() + model.log_cycle() ### NOTE setting the flag causes the regrid step to be skipped self.set_input_forcings_skip_flags() - ( - future_time, - config_options, - geo_meta, - input_forcing_mod, - supp_pcp_mod, - mpi_config, - output_obj, - input_forcings, - ) = model.loop_through_forcing_products( - future_time, - config_options, - geo_meta, - input_forcing_mod, - supp_pcp_mod, - mpi_config, - output_obj, - ) + model.loop_through_forcing_products(future_time) # Update test fixture status self._state = "pre_ran" @@ -622,7 +578,7 @@ def pre_regrid(self) -> None: def set_input_forcings_skip_flags(self) -> None: """Set the `skip` flag on the InputForcings object so that forcing regrid will not occur during loop_through_forcing_products().""" logging.debug( - "Setting input_forcing.skip = True for each value in dict self.input_forcing_mod" + "Setting input_forcing.skip = True for each value in dict self.bmi_model._input_forcing_mod" ) for force_key, input_forcing in self.bmi_model._input_forcing_mod.items(): input_forcing.skip = True