Fetching and Summarizing NWM Gridded Data#

Overview#

In this guide we’ll demonstrate fetching National Water Model (NWM) operational and retrospective gridded data from cloud storage. This example makes use of a pre-generated Evaluation dataset stored in TEEHR’s example data module.

Note: For demonstration purposes several cells below are shown in markdown form. If you want to download this notebook and run them yourself, you will need to convert them to code cells.

Set up the example Evaluation#

from pathlib import Path
import shutil
import pandas as pd
import hvplot.pandas

from teehr.example_data.setup_nwm_grid_example import setup_nwm_example
import teehr
from teehr.evaluation.utils import print_tree

# Tell Bokeh to output plots in the notebook
from bokeh.io import output_notebook
output_notebook()
Loading BokehJS ...

We’ll start with the Evaluation from the previous User Guide, which contains observed (USGS) and simulation (NWM) streamflow for a gage at Radford, VA during hurricane Helene.

# Define the directory where the Evaluation will be created.
test_eval_dir = Path(Path().home(), "temp", "11_fetch_gridded_nwm_data")

# Setup the example evaluation using data from the TEEHR repository.
shutil.rmtree(test_eval_dir, ignore_errors=True)
setup_nwm_example(tmpdir=test_eval_dir)

# Initialize the evaluation.
ev = teehr.Evaluation(dir_path=test_eval_dir)

Hide code cell output

---------------------------------------------------------------------------
PySparkRuntimeError                       Traceback (most recent call last)
Cell In[2], line 6
      2 test_eval_dir = Path(Path().home(), "temp", "11_fetch_gridded_nwm_data")
      3 
      4 # Setup the example evaluation using data from the TEEHR repository.
      5 shutil.rmtree(test_eval_dir, ignore_errors=True)
----> 6 setup_nwm_example(tmpdir=test_eval_dir)
      7 
      8 # Initialize the evaluation.
      9 ev = teehr.Evaluation(dir_path=test_eval_dir)

File ~/work/teehr/teehr/src/teehr/example_data/setup_nwm_grid_example.py:13, in setup_nwm_example(tmpdir)
     11 """Set up the NWM streamflow fetching example."""
     12 # Create an Evaluation object and create the directory
---> 13 ev = teehr.LocalReadWriteEvaluation(dir_path=tmpdir, create_dir=True)
     15 # Fetch the test data
     16 location_data_path = Path(tmpdir, "usgs_at_radford_location.parquet")

File ~/work/teehr/teehr/src/teehr/evaluation/evaluation.py:778, in LocalReadWriteEvaluation.__init__(self, dir_path, create_dir, check_evaluation_version, spark, namespace_name, enable_spark_proxy)
    745 def __init__(
    746     self,
    747     dir_path: Union[str, Path],
   (...)    752     enable_spark_proxy: bool = False,
    753 ):
    754     """Initialize the Evaluation class.
    755 
    756     Parameters
   (...)    776         access to the underlying Spark DataFrame. Default is False.
    777     """
--> 778     super().__init__(
    779         spark=spark,
    780         dir_path=Path(dir_path),
    781         enable_spark_proxy=enable_spark_proxy,
    782     )
    784     local_catalog_name = self.spark.conf.get("local_catalog_name")
    785     warehouse_dir = self.dir_path / local_catalog_name

File ~/work/teehr/teehr/src/teehr/evaluation/evaluation.py:105, in BaseEvaluation.__init__(self, dir_path, spark, enable_spark_proxy)
    103 else:
    104     logger.info("Creating a new default Spark session.")
--> 105     self.spark = create_spark_session()

File ~/work/teehr/teehr/src/teehr/evaluation/spark_session_utils.py:300, in create_spark_session(app_name, local_catalog_name, local_catalog_type, remote_warehouse_dir, remote_catalog_name, remote_catalog_type, remote_catalog_uri, start_spark_cluster, force_recreate_session, executor_instances, executor_memory, executor_cores, executor_image, executor_namespace, driver_memory, driver_max_result_size, pod_template_path, aws_access_key_id, aws_secret_access_key, aws_session_token, aws_region, aws_profile, enable_gcs, gcs_project_id, gcs_service_account_key_file, add_jars, add_packages, update_configs, debug_config, polaris_token, use_authmanager)
    292 _update_configs_and_packages(
    293     conf=conf,
    294     update_configs=effective_configs or None,
    295     add_jars=add_jars,
    296     add_packages=add_packages
    297 )
    299 logger.info("⚙️ All settings applied. Creating Spark session...")
--> 300 spark = SparkSession.builder.appName(app_name).config(conf=conf).getOrCreate()
    301 sedona_spark = SedonaContext.create(spark)
    303 if debug_config:

File /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/pyspark/sql/session.py:556, in SparkSession.Builder.getOrCreate(self)
    554     sparkConf.set(key, value)
    555 # This SparkContext may be an existing one.
--> 556 sc = SparkContext.getOrCreate(sparkConf)
    557 # Do not update `SparkConf` for existing `SparkContext`, as it's shared
    558 # by all sessions.
    559 session = SparkSession(sc, options=self._options)

File /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/pyspark/core/context.py:523, in SparkContext.getOrCreate(cls, conf)
    521 with SparkContext._lock:
    522     if SparkContext._active_spark_context is None:
--> 523         SparkContext(conf=conf or SparkConf())
    524     assert SparkContext._active_spark_context is not None
    525     return SparkContext._active_spark_context

File /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/pyspark/core/context.py:205, in SparkContext.__init__(self, master, appName, sparkHome, pyFiles, environment, batchSize, serializer, conf, gateway, jsc, profiler_cls, udf_profiler_cls, memory_profiler_cls)
    199 if gateway is not None and gateway.gateway_parameters.auth_token is None:
    200     raise ValueError(
    201         "You are trying to pass an insecure Py4j gateway to Spark. This"
    202         " is not allowed as it is a security risk."
    203     )
--> 205 SparkContext._ensure_initialized(self, gateway=gateway, conf=conf)
    206 try:
    207     self._do_init(
    208         master,
    209         appName,
   (...)    219         memory_profiler_cls,
    220     )

File /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/pyspark/core/context.py:444, in SparkContext._ensure_initialized(cls, instance, gateway, conf)
    442 with SparkContext._lock:
    443     if not SparkContext._gateway:
--> 444         SparkContext._gateway = gateway or launch_gateway(conf)
    445         SparkContext._jvm = SparkContext._gateway.jvm
    447     if instance:

File /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/pyspark/java_gateway.py:111, in launch_gateway(conf, popen_kwargs)
    108     time.sleep(0.1)
    110 if not os.path.isfile(conn_info_file):
--> 111     raise PySparkRuntimeError(
    112         errorClass="JAVA_GATEWAY_EXITED",
    113         messageParameters={},
    114     )
    116 with open(conn_info_file, "rb") as info:
    117     gateway_port = read_int(info)

PySparkRuntimeError: [JAVA_GATEWAY_EXITED] Java gateway process exited before sending its port number.
ev.locations.to_geopandas()

We can add polygons to summarize rainfall to, to see the impact of the forcing data on the NWM streamflow prediction

location_data_path = Path(test_eval_dir, "three_huc10s_radford.parquet")

ev.locations.load_spatial(
    location_data_path,
    field_mapping={
        "huc10": "id"
    },
    location_id_prefix="wbd",
    write_mode="append"  # this is the default
)

Now we have the USGS gage point, and three WBD HUC10 polygons in the locations table.

gdf = ev.locations.to_geopandas()
gdf
gdf[gdf.id != "usgs-03171000"].hvplot(geo=True, tiles="OSM", alpha=0.5) * \
    gdf[gdf.id == "usgs-03171000"].hvplot(geo=True, color="black", size=50)

Now we’ll fetch NWM gridded analysis and assimilation rainfall data and calculate mean areal precipitation (MAP) for each of the HUC10 watersheds. We’ll consider this “observed” primary timeseries.

The location ID prefix is used to filter the locations table for WBD polygons during fetching. The calculated MAP timeseries will be appended (the default) to the primary_timeseries table along with the streamflow data (the primary timeseries table will contain both streamflow and rainfall).

# To run this cell locally first convert it to a python cell
ev.fetch.nwm_operational_grids(
    nwm_configuration="forcing_analysis_assim",
    output_type="forcing",
    variable_name="RAINRATE",
    start_date=datetime(2024, 9, 26),
    end_date=datetime(2024, 9, 26),
    nwm_version="nwm30",
    prioritize_analysis_value_time=True,
    t_minus_hours=[0],
    calculate_zonal_weights=True,
    location_id_prefix="wbd",
    timeseries_type="primary"  # To be considered "observations". This is the default.
)
primary_df = ev.primary_timeseries.to_pandas()
primary_df.head()

Let’s take a look at the cache directory. After fetching the NWM analysis forcing, we have a directory for the weights file.

print_tree(Path(ev.cache_dir, "fetching", "weights"))

The weights file contains the fractional coverage for each pixel (row/col pair) that intersects with each polygon location (WBD HUC10 watershed).

cached_weights_filepath = Path(
        ev.cache_dir,
        "fetching",
        "weights",
        "nwm30_forcing_analysis_assim",
        "nwm30_forcing_analysis_assim_pixel_weights.parquet"
)
pd.read_parquet(cached_weights_filepath)

Now we can fetch the NWM forecast rainfall and calculate MAP, to compare it to the “observed” rainfall. First we need to create and import the location_crosswalks table, which maps the secondary locations (“model”) to the primary (“observations”).

ev.locations.to_pandas()["id"].unique()
xwalk_df = pd.DataFrame(
    {
        "primary_location_id": [
            "wbd-0505000115",
            "wbd-0505000117",
            "wbd-0505000118"
        ],
        "secondary_location_id": [
            "forecast-0505000115",
            "forecast-0505000117",
            "forecast-0505000118"
        ]
    }
)
temp_xwalk_path = Path(ev.cache_dir, "forcing_xwalk.parquet")
xwalk_df.to_parquet(temp_xwalk_path)

Now we can load it into the Evaluation, appending to the existing table.

ev.location_crosswalks.load_parquet(temp_xwalk_path)
ev.location_crosswalks.to_pandas()

Now we can fetch the NWM forecast rainfall, which we’ll consider the “secondary” timeseries. Let’s grab a single short range rainfall forecast

# To run this cell locally first convert it to a python cell
ev.fetch.nwm_operational_grids(
    nwm_configuration="forcing_short_range",
    output_type="forcing",
    variable_name="RAINRATE",
    start_date=datetime(2024, 9, 26),
    end_date=datetime(2024, 9, 26),
    nwm_version="nwm30",
    location_id_prefix="forecast",
    calculate_zonal_weights=False,  # re-use the weights file in the cache
    zonal_weights_filepath=cached_weights_filepath,
    starting_z_hour=1,
    ending_z_hour=1,
    timeseries_type="secondary"  # now considered forecast
)

And our secondary_timeseries table consists of NWM medium range streamflow forecasts (member 1), plus NWM short range rainfall forecast summarized to the three WBD HUC10 watersheds as mean areal precipitation (MAP).

secondary_df = ev.secondary_timeseries.to_pandas()
secondary_df.head()

And our primary_timeseries table consists of USGS streamflow data at the Radford gage, plus NWM analysis rainfall summarized to the three WBD HUC10 watersheds as mean areal precipitation (MAP).

primary_df = ev.primary_timeseries.to_pandas()
primary_df.head()

Now we can make use of the joined_timeseries_view for efficient metric calculation and further exploration.

joined_df = ev.joined_timeseries_view().to_pandas()
joined_df.head()
joined_df.secondary_configuration_name.unique()
# We'll use this helper function for plotting timeseries.
def plot_timeseries(
    configuration_name: str,
    secondary_by: list[str],
    title: str
):
    sim_plot = joined_df[joined_df["secondary_configuration_name"] == configuration_name].\
        hvplot(
            x="value_time",
            y="secondary_value",
            by=secondary_by,
            legend=False,
            )
    obs_plot = joined_df[joined_df["secondary_configuration_name"] == configuration_name].\
        hvplot(
            x="value_time",
            y="primary_value",
            by=["location_id", "secondary_configuration_name"],
            legend=False,
            color="black"
            )
    return (sim_plot * obs_plot).options(
                width=700,
                height=400,
                show_grid=True,
                title=title
            )

We can plot the primary (USGS) vs. secondary (NWM) streamflow and notice that this particular NWM forecast underestimated the flow.

plot_timeseries(
    configuration_name="nwm30_medium_range",
    secondary_by=["reference_time"],
    title="Observed streamflow (black) and forecast streamflow at the Radford gage"
)

In plotting the primary vs. secondary rainfall (MAP) in each watershed, we can see the this NWM forecast underestimated the observed rainfall. This is likely one reason why the NWM streamflow forecasts also underestimated the flow.

plot_timeseries(
    configuration_name="nwm30_forcing_short_range",
    secondary_by=["location_id"],
    title="Observed MAP (black) and forecast MAP at the three HUC10s"
)

Now we can also calculate performance metrics for the streamflow and rainfall for this event.

bias = teehr.DeterministicMetrics.RelativeBias()
kge = teehr.DeterministicMetrics.KlingGuptaEfficiency()

ev.joined_timeseries_view().aggregate(
    metrics=[bias, kge],
    group_by=["location_id", "secondary_configuration_name"],
).order_by(["location_id", "secondary_configuration_name"]).to_pandas()
ev.spark.stop()