Evaluating Ensemble Streamflow Forecasts#

Overview#

This notebook introduces using TEEHR to evaluate ensemble forecasts. Note that ensemble analysis in TEEHR is currently ongoing, and additional metrics and analyses are in development.

In this exercise we will use a pre-existing evaluation stored in the TEEHR repository consisting of two USGS gage locations with Hydrologic Ensemble Forecasting System (HEFS) forecasts from CNRFC.

Set up the example Evaluation#

import shutil
from pathlib import Path

import teehr
from teehr.example_data.setup_ensemble_example import setup_hefs_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", "09_ensemble_metrics")
shutil.rmtree(test_eval_dir, ignore_errors=True)

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

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

File ~/work/teehr/teehr/src/teehr/example_data/setup_ensemble_example.py:11, in setup_hefs_example(tmpdir)
      9 """Set up the ensemble metrics 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, "two_locations.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.

Explore the evaluation data#

In this example we have two USGS gage locations corresponding to CNRFC forecast points.

locations_gdf = ev.locations.to_geopandas()
locations_gdf

The secondary location IDs correspond to the CNRFC forecast point IDs.

ev.location_crosswalks.to_pandas()

The primary timeseries are the USGS gage observations.

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

The secondary timeseries are the CNRFC HEFS ensemble forecasts corresponding to each location.

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

HEFS is probabilistic and each forecast consists of several ensemble traces or members. In TEEHR,each trace is represented by the member column in the timeseries table schema.

In this case each forecast contains 42 members.

st_df.member.unique().size

Let’s visualize the data. We’ll use some helper functions to plot the forecasts against the USGS gage data. Note that visualization functionality within TEEHR is in-development.

import pandas as pd
import hvplot.pandas  # noqa
def plot_teehr_timeseries(
    df: pd.DataFrame,
    x_column: str = "value_time",
    y_column: str = "value",
    title: str = None
):
    columns = df.columns
    variable_columns = [col for col in columns if df[col].nunique() > 1]
    variable_columns.remove(x_column)
    variable_columns.remove(y_column)
    figure = df.hvplot(x="value_time", y="value", by=variable_columns)
    return figure.options(
        width=700,
        height=400,
        show_grid=True,
        title=title
    )
# Get the HEFS forecast for location SCBC1.
st_df = ev.secondary_timeseries.filter("location_id == 'SCBC1'").to_pandas()

# Create a line plot of the corresponding USGS observed flow data.
usgs_plot = pt_df[pt_df.location_id == "usgs-11402000"].hvplot(x="value_time", y="value").options(line_width=3, line_dash="dashed", color="black")

# Create a line plot of the HEFS forecast data with the USGS observed flow data.
(plot_teehr_timeseries(st_df, title="SCBC1 HEFS Ensemble vs. USGS") * usgs_plot).options(show_legend=False)
# Get the HEFS forecast for location MRYC1.
st_df = ev.secondary_timeseries.filter("location_id == 'MRYC1'").to_pandas()

# Create a line plot of the corresponding USGS observed flow data.
usgs_plot = pt_df[pt_df.location_id == "usgs-11421000"].hvplot(x="value_time", y="value").options(line_width=3, line_dash="dashed", color="black")

# Create a line plot of the HEFS forecast data with the USGS observed flow data.
(plot_teehr_timeseries(st_df, title="MRYC1 HEFS Ensemble vs. USGS") * usgs_plot).options(show_legend=False)

Calculating the Continuous Ranked Probability Score (CRPS)#

The continuous ranked probability score (CRPS) is a common metric used to evaluate the performance of ensemble forecasts. TEEHR implements CRPS through the scoringrules library.

We can define a CRPS metric object and customize it’s parameters in the same way we defined metrics in previous examples.

crps = teehr.ProbabilisticMetrics.CRPS()

# Specify the estimator to use.
#   "pwm" - Probability Weighted Moment form (default)
#   "nrg" - Energy form
#   "fair" - Fair version of energy form
crps.estimator = "pwm"

# Specify the backend to use.
#   "numba" - Use the numba library for calculations (default)
#   "numpy" - Use the numpy library for calculations
crps.backend = "numba"

# Return the per-time-step scores instead of summarizing them.
crps.summary_statistic = None

crps.output_field_name = "crps_ensemble"
ev.joined_timeseries_view().aggregate(
    metrics=[crps],
    group_by=[
        "location_id",
        "reference_time",
        "secondary_configuration_name"
    ],
).order_by("location_id").to_pandas()

With summary_statistic=None, CRPS returns an array of scores for each value time. Setting it to "mean" (the default) or "median" summarizes them.

crps.summary_statistic = "mean"

crps.output_field_name = "mean_crps_ensemble"
ev.joined_timeseries_view().aggregate(
    metrics=[crps],
    group_by=[
        "location_id",
        "reference_time",
        "secondary_configuration_name"
    ],
).order_by("location_id").to_pandas()

Summary#

Currently only the CRPS is implemented in TEEHR however additonal metrics and functionality is ongoing including ensemble timeseries visualization, skill score calculation, Brier Score, and more.

ev.spark.stop()