Fetching USGS and NWM Streamflow Data#

Overview#

In this guide we’ll demonstrate fetching National Water Model (NWM) streamflow forecasts from Google Cloud Storage (GCS). This example makes use of a pre-generated Evaluation dataset stored in TEEHR’s examples data module. It contains a single USGS gage location and the corresponding NWM location ID.

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.

For a refresher on loading location and location crosswalk data into a new Evaluation refer back to the Loading Data section of the user guide.

Set up the example Evaluation#

from pathlib import Path
import shutil

import teehr
from teehr.example_data.setup_nwm_streamflow_example import setup_nwm_example

# Tell Bokeh to output plots in the notebook
from bokeh.io import output_notebook
output_notebook()
Loading BokehJS ...
# Define the directory where the Evaluation will be created.
test_eval_dir = Path(Path().home(), "temp", "10_fetch_nwm_data")
shutil.rmtree(test_eval_dir, ignore_errors=True)

# Setup the example evaluation using data from the TEEHR repository.
setup_nwm_example(tmpdir=test_eval_dir)

# Initialize the evaluation.
ev = teehr.Evaluation(dir_path=test_eval_dir)
---------------------------------------------------------------------------
PySparkRuntimeError                       Traceback (most recent call last)
Cell In[2], line 6
      2 test_eval_dir = Path(Path().home(), "temp", "10_fetch_nwm_data")
      3 shutil.rmtree(test_eval_dir, ignore_errors=True)
      4 
      5 # Setup the example evaluation using data from the TEEHR repository.
----> 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_streamflow_example.py:11, in setup_nwm_example(tmpdir)
      9 """Set up the NWM streamflow fetching example."""
     10 # Create an Evaluation object and create the directory
---> 11 ev = teehr.LocalReadWriteEvaluation(dir_path=tmpdir, create_dir=True)
     13 # Fetch the test data
     14 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.

This example Evaluation only contains a single location, the USGS gage on the New River at Radford, VA.

locations_gdf = ev.locations.to_geopandas()
locations_gdf

The ID of the National Water Model reach corresponding to the USGS gage is in the location crosswalks table.

location_crosswalks_df = ev.location_crosswalks.to_pandas()
location_crosswalks_df

Location ID Prefixes#

Note that the fetching methods automatically append location ID prefixes to the USGS and NWM location IDs. These must existing the location and location crosswalk tables first. See the Loading Local Data user guide for more info on specifying the location ID prefix when loading data.

Fetching USGS streamgage data#

Since the example Evalution already contains the location and location crosswalk IDs for USGS and NWM locations, we can make use of TEEHR’s built-in tools to fetch USGS and NWM streamflow data.

First we’ll fetch USGS data from the National Water Information System (NWIS). TEEHR makes use of the USGS dataretrieval python tool under the hood.

Note that the USGS and NWM streamflow timeseries data have been pre-loading into this example Evaluation. However you can still download this notebook and execute the methods yourself.

ev.fetch.usgs_streamflow() is a method that fetches the USGS data for the primary locations in the evaluation. It requires users to define the start and end times of data to fetch and has several optional arguments. For more details on the method see:

We’ll fetch streamflow data at this gage during the 2024 Hurricane Helene event.

# Convert this to a code cell to run locally
ev.fetch.usgs_streamflow(
    start_date=datetime(2024, 9, 26),
    end_date=datetime(2024, 10, 1)
)

TEEHR automatically loads the data into the Evaluation. USGS data is loaded a primary timeseries by default.

df = ev.primary_timeseries.to_pandas()
df

Appending, Upserting, and Overwriting data#

Note that the fetching methods allow you to add new data to an existing table (append, the default) or replace existing data with new values while adding additional data (upsert). These are available through the write_mode argument. Additionally, when write_mode="overwrite", any existing partitions receiving new data will be overwritten.

ex:

ev.fetch.usgs_streamflow(
    start_date=datetime(2024, 10, 1),
    end_date=datetime(2024, 10, 5),
    write_mode="append"
)

Fetching NWM streamflow data#

ev.fetch.nwm_operational_points() is a method that fetches near real-time NWM point data (e.g., streamflow) from Google Cloud Storage. This method fetches data for the secondary location IDs listed in the location_crosswalks table, and automatically loads the time series into the secondary_timeseries Evaluation table.

There are several required arguments to define when using the method, including the NWM configuration, NWM variable name, start date, number of ingest days, and others. Several optional arguments are also available.

We’ll now fetch streamflow forecasts for the NWM location corresponding to the USGS gage.

Note

TEEHR fetches NWM data concurrently by default. See teehr.utils.concurrency.set_concurrency to tune how many files are read at once on machines with more or fewer resources.

# Convert this to a code cell to run locally
ev.fetch.nwm_operational_points(
    nwm_configuration="medium_range_mem1",
    output_type="channel_rt_1",
    variable_name="streamflow",
    start_date=datetime(2024, 9, 26),
    end_date=datetime(2024, 9, 26),
    nwm_version="nwm30",
)

Here we are fetching NWM version 3.0 Medium Range streamflow forecast, ensemble member 1, for the same time period as the USGS data.

A list of available NWM configurations for point data is shown below. Appropriate values for the output_type and variable_name arguments depend on the specified nwm_configuration value.

More information on NWM configurations can be found here: https://water.noaa.gov/about/nwm

from teehr.fetching.models.nwm30_point import ConfigurationsEnum
list(ConfigurationsEnum.__members__)
df = ev.secondary_timeseries.to_pandas()
df

Now you calculate metrics comparing the NWM forecasts to the USGS observations by using the joined_timeseries_view.

ev.spark.stop()

Additional NWM fetching methods in TEEHR#

NWM Retrospective Point Data#

NWM retrospective point data for versions 2.0, 2.1, and 3.0:

Fetch.nwm_retrospective_points

Fetch NWM retrospective point data and load into the TEEHR dataset.

NWM Retrospective and Forecast Gridded Data#

NWM gridded data can also be fetched in TEEHR. Gridded data is summarized to zones (polygons) as the zonal mean.

Fetch.nwm_operational_grids

Fetch NWM operational gridded data, calculate zonal statistics (currently only mean is available) of selected variable for given zones, and load into the TEEHR dataset.

Fetch.nwm_retrospective_grids

Fetch NWM retrospective gridded data, calculate zonal statistics (currently only mean is available) of selected variable for given zones, and load into the TEEHR dataset.