Overview

This document describes the repeatable workflow for generating a hydrometric station’s upstream watershed and an hourly runoff-impact map. A watershed is the area of land that drains into a particular river station. The runoff-impact map shows how much water is expected to run across the ground and into the river for a given forecast hour.

The workflow is implemented by the WTF Backend (Water Terrain Forecast) development team, and uses Python web services to send traffic over FastAPI.


Goal

Given a station number (for example 07AA002), produce:

  • The station’s upstream watershed boundary.
  • A forecast-driven runoff-impact map with five classes: None, Low, Moderate, High, and Severe.
  • Summary statistics such as watershed area, mean elevation, pixel counts per class, and total runoff volume.

Deployment

Prerequisites

  1. DEM (Digital Elevation Model) file. The default path is src/notebook/data/jasper_study_area_dem.tif. You can override it with the DEM_PATH environment variable. See line 11 in src/app/config.py.

  2. A .env file with valid values for:

    • SUPABASE_URL and SUPABASE_KEY (the Supabase database credentials).
    • API_KEY (used by the X-API-Key header for authentication).
    • ENVIROVISION_API_BASE_URL point to 127.0.0.1:8000 or target upstream VPS
    • Optional: ENVIROVISION_API_KEY for the upstream service.
    • Failover addresses can be configured. See lines 54 to 57 in src/app/config.py.
  3. Be sure to install MAKE or Docker for deployment purposes.

  4. Minimum storage: 5GB, highly recommend having more. If docker system prune is anything to go by, bump it up to 12Gb storage minimum.

Example .env file:

SUPABASE_URL=https://xtbzu.supabase.co
SUPABASE_KEY=sb_publishable_3nAFK--v3yBABaTHcgpvIg_nnnnnnnn
API_KEY=KNf92cichmodx_0l644DQh2crzRqXJzM7Unnnnnnnn
API_AUTH_ENABLED=false
ENVIROVISION_API_BASE_URL=http://127.0.0.1:8000/api/v1
CORS_ORIGINS=http://localhost:3000,http://frontend.wtf.dns

note: Highly recommend that CORS_ORIGINS authenticates over DNS, as adding individual IP addresses can be cumbersome balancing LAN and remote clients.

Deploy with Makefile

make dev

make reads commands from the Makefile. Services wil run on port 8000 unless configured differently.

Deploy with Docker

For easy deployment use:

docker-compose up -d

Services wil run on port 8888 unless configured otherwise.


Pipeline overview

  1. Start the server. The DEM is loaded and conditioned once at startup.
  2. List available stations from the Supabase hydrometric_stations table.
  3. Request the watershed endpoint for the station.
  4. The service snaps the station to the nearest stream cell, delineates the catchment, and collects sample points inside it.
  5. Weather forecasts are fetched for each sample point.
  6. The target forecast hour is selected (the wettest common hour by default).
  7. Rainfall is interpolated across the watershed and converted to runoff.
  8. Runoff is routed downstream and classified into five impact classes.
  9. The service returns a JSON (JavaScript Object Notation) response with statistics, a boundary, and a map image.

Step-by-step details

1. DEM load and conditioning (on startup)

File: src/app/hydro.py lines 260-309

DemModel.__init__ reads the DEM and prepares it for analysis:

  • Fills pits, depressions, and flats in the terrain model.
  • Computes flow direction (which way water flows from each pixel).
  • Computes flow accumulation (how many upstream pixels drain through each pixel).

These results are saved to disk in data/cache so the next startup is faster. See src/app/hydro.py lines 320 to 412, for the cache logic.

2. Station list

Endpoint:

GET /api/v1/get-hydrometric-stations/

File: src/app/routes/get_hydrometric_stations.py line 96

Returns stations stored in Supabase. Each station has a station_number, station_name, watercourse, latitude, and longitude.

3. Watershed request

Endpoint:

GET /api/v1/get-hydrometric-stations/{station_number}/watershed

File: src/app/routes/get_hydrometric_stations.py lines 100 to 118

Query parameters:

ParameterTypeDefaultDescription
runoff_coefficientfloat0.6Fraction of rain that becomes runoff, from 0 to 1.
reference_coefficientfloatnullOptional fixed coefficient used only to keep class thresholds stable.
hourstringnullOptional ISO 8601 forecast hour. If omitted, the wettest common hour is used.

4. Station preparation and catchment delineation

File: src/app/hydro.py lines 515 to 545

The prepare method:

  • Reprojects the station coordinates from WGS84 (the global latitude and longitude system, also known as EPSG:4326) into the DEM’s own coordinate system.
  • Checks that the station lies inside the DEM bounds.
  • Snaps the outlet to the highest-flow-accumulation cell within a 5-pixel window (src/app/hydro.py line 416).
  • Runs grid.catchment to delineate the upstream area.
  • Selects up to 49 sample points inside the watershed (src/app/hydro.py line 431).

5. Forecast fetch

File: src/app/lib/weather.py line 99

Forecasts are fetched concurrently for all sample points. The backend calls its own weather proxy endpoint, which in turn queries Open-Meteo (a free weather API). Each request includes the X-API-Key header and is retried on transient failures.

6. Target hour selection

File: src/app/hydro.py line 685

The backend finds the common future forecast hours across all sample points. If hour is not provided, it picks the hour with the highest average rainfall.

7. Rainfall interpolation

File: src/app/hydro.py line 793 to 826

Rainfall values at the sample points are spread across the catchment using radial basis function (RBF) interpolation. See the dedicated section below for details.

8. Runoff routing and classification

File: src/app/hydro.py lines 932 to 988

  • Rainfall is multiplied by runoff_coefficient and by each cell’s area to get runoff volume.
  • Runoff is routed downstream using the flow-direction grid.
  • Impact classes are defined by percentiles of the routed positive values:
ClassMeaningRange
0NoneNo runoff, or outside the watershed.
1LowBelow the p50 (50th percentile, or median).
2ModerateBetween p50 and p75.
3HighBetween p75 and p90.
4SevereGreater than or equal to p90.

9. Output

File: src/app/routes/get_hydrometric_stations.py lines 254 to 292

The response is JSON and contains:

  • Station, outlet, watershed area, and mean elevation.
  • Hourly rainfall averages and per-sample-point forecasts.
  • The watershed boundary as GeoJSON (a JSON format for geographic shapes).
  • The impact map as a PNG (Portable Network Graphics) image encoded as a data URI (Uniform Resource Identifier), using RGBA color (red, green, blue, alpha transparency).
  • Class counts, percentile thresholds, and current weather.

Nothing is written to disk or to Supabase.


Workflow example: station 07AA002

  1. Start the server:

    make dev
  2. Check health:

    curl -H "X-API-Key: $API_KEY" http://localhost:8000/health

    A degraded status usually means the DEM is missing or DEM_PATH is wrong. See /health in src/app/main.py lines 149 to 169.

  3. Request the watershed map:

    curl -G \
      -H "X-API-Key: $API_KEY" \
      http://localhost:8000/api/v1/get-hydrometric-stations/07AA002/watershed \
      -d "runoff_coefficient=0.6"

    To use a specific forecast hour, first inspect the hourly list in the response, then repeat the request with, for example:

    -d "hour=2026-05-20T18:00"
  4. Inspect the response. Useful fields to check:

    • area_km2 and mean_elevation_m: confirm the watershed looks reasonable.
    • hourly: rainfall per forecast hour across the watershed.
    • class_counts: how many pixels fall in each impact class.
    • image: the base64-encoded PNG map with corner coordinates.

How rainfall is interpolated

The app uses RBF interpolation to estimate rainfall at every pixel inside the watershed from the rainfall values at the sample points.

RBF is a function whose value depends only on distance from a center point. The interpolation builds a smooth surface by combining one such function for each sample point. The weights are chosen so the surface matches all observed rainfall values exactly. The code uses the multiquadric kernel:

φ(r) = √(r² + ε²)

where:

  • r is the distance from a sample point.
  • ε is a shape parameter that controls how smooth or sharp the surface is.

For performance, _rainfall_surface (src/app/hydro.py line 793) evaluates the RBF on a coarse grid (every 25th cell) and then upscales to full resolution with bilinear interpolation. A full-resolution version, _rainfall_surface_full (src/app/hydro.py line 828), exists only for testing so the coarse approach can be validated. See tests/test_hydro.py for the parity checks.

Caveats:

  • RBF works best inside the area covered by the sample points.
  • Extrapolation beyond those points can be unreliable.
  • A bad shape parameter can cause overshoots or ringing artifacts.
  • If all sample points have the same rainfall, or fewer than four points exist, the surface is set to a flat average instead.

Caching

Several caches speed up repeated requests:

  • Result cache (src/app/lib/cache.py line 17): keeps full watershed responses in memory for a TTL (time to live) of 900 seconds and up to 32 items. The LRU (least recently used) item is removed when the cache is full. Cache keys include station number, coefficients, hour, and a version number (src/app/routes/get_hydrometric_stations.py:167-174).
  • Station list cache: stored on the app state for 3600 seconds.
  • Terrain cache: DEM conditioning results are saved to data/cache (.gitignore set so cache is not committed to version control).
  • Analysis lock: a single-slot lock (main.py line 49) prevents two heavy terrain calculations from running at the same time.

To force a fresh calculation, change runoff_coefficient slightly or wait for the TTL to expire.


Verification

Use the existing project commands:

  • Run tests:

    make test

    tests/test_hydro.py checks the watershed math for station 07AA002. tests/test_api.py checks the endpoints, including cache behavior and error cases.

  • Lint the code:

    make lint

    This runs ruff, a Python linter and code formatter.

  • Smoke test the endpoint with curl (a command-line tool for HTTP requests):

    curl -G \
      -H "X-API-Key: $API_KEY" \
      http://localhost:8000/api/v1/get-hydrometric-stations/07AA002/watershed \
      -d "runoff_coefficient=0.6"

Troubleshooting

SymptomLikely causeFix
/health returns degradedDEM file is missing or DEM_PATH is wrong.Place the DEM at src/notebook/data/jasper_study_area_dem.tif or set DEM_PATH.
503 on watershed requestDemModel failed to load at startup.Check server logs for the original FileNotFoundError or conditioning error.
404 on watershed requestUnknown station number.Call GET /api/v1/get-hydrometric-stations/ to list valid numbers.
422 on watershed requestStation is outside the DEM coverage.Use a station that lies inside the DEM bounds.
502 on watershed requestUpstream weather API failed.Check ENVIROVISION_API_BASE_URL, ENVIROVISION_API_KEY, and network connectivity.
Map looks flat or uniformVery low rainfall, or fewer than four sample points.Check the hourly rainfall values in the response.
Repeated requests return instantlyResult cache hit.Wait for TTL expiry or vary parameters slightly.

  • src/app/hydro.py — terrain conditioning, catchment delineation, rainfall interpolation, runoff routing, and classification.
  • src/app/lib/weather.py — forecast fetching and retry logic.
  • src/app/routes/get_hydrometric_stations.py — the watershed endpoint.
  • src/app/main.py — application setup, DEM loading, and /health.
  • src/app/config.py — environment settings such as DEM_PATH and weather URLs.
  • tests/test_hydro.py and tests/test_api.py — automated checks.