Backend
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
DEM (Digital Elevation Model) file. The default path is
src/notebook/data/jasper_study_area_dem.tif. You can override it with theDEM_PATHenvironment variable. See line 11 insrc/app/config.py.A
.envfile with valid values for:SUPABASE_URLandSUPABASE_KEY(the Supabase database credentials).API_KEY(used by theX-API-Keyheader for authentication).ENVIROVISION_API_BASE_URLpoint to127.0.0.1:8000or target upstream VPS- Optional:
ENVIROVISION_API_KEYfor the upstream service. - Failover addresses can be configured. See lines 54 to 57 in
src/app/config.py.
Minimum storage: 5GB, highly recommend having more. If
docker system pruneis 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.dnsnote: 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 devmake reads commands from the Makefile. Services wil run on port 8000 unless configured differently.
Deploy with Docker
For easy deployment use:
docker-compose up -dServices wil run on port 8888 unless configured otherwise.
Pipeline overview
- Start the server. The DEM is loaded and conditioned once at startup.
- List available stations from the Supabase
hydrometric_stationstable. - Request the watershed endpoint for the station.
- The service snaps the station to the nearest stream cell, delineates the catchment, and collects sample points inside it.
- Weather forecasts are fetched for each sample point.
- The target forecast hour is selected (the wettest common hour by default).
- Rainfall is interpolated across the watershed and converted to runoff.
- Runoff is routed downstream and classified into five impact classes.
- 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}/watershedFile: src/app/routes/get_hydrometric_stations.py lines 100 to 118
Query parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
runoff_coefficient | float | 0.6 | Fraction of rain that becomes runoff, from 0 to 1. |
reference_coefficient | float | null | Optional fixed coefficient used only to keep class thresholds stable. |
hour | string | null | Optional 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.pyline 416). - Runs
grid.catchmentto delineate the upstream area. - Selects up to 49 sample points inside the watershed (
src/app/hydro.pyline 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_coefficientand 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:
| Class | Meaning | Range |
|---|---|---|
| 0 | None | No runoff, or outside the watershed. |
| 1 | Low | Below the p50 (50th percentile, or median). |
| 2 | Moderate | Between p50 and p75. |
| 3 | High | Between p75 and p90. |
| 4 | Severe | Greater 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
Start the server:
make devCheck health:
curl -H "X-API-Key: $API_KEY" http://localhost:8000/healthA
degradedstatus usually means the DEM is missing orDEM_PATHis wrong. See/healthinsrc/app/main.pylines 149 to 169.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
hourlylist in the response, then repeat the request with, for example:-d "hour=2026-05-20T18:00"Inspect the response. Useful fields to check:
area_km2andmean_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:
ris 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.pyline 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(.gitignoreset so cache is not committed to version control). - Analysis lock: a single-slot lock (
main.pyline 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 testtests/test_hydro.pychecks the watershed math for station07AA002.tests/test_api.pychecks the endpoints, including cache behavior and error cases.Lint the code:
make lintThis 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
| Symptom | Likely cause | Fix |
|---|---|---|
/health returns degraded | DEM 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 request | DemModel failed to load at startup. | Check server logs for the original FileNotFoundError or conditioning error. |
404 on watershed request | Unknown station number. | Call GET /api/v1/get-hydrometric-stations/ to list valid numbers. |
422 on watershed request | Station is outside the DEM coverage. | Use a station that lies inside the DEM bounds. |
502 on watershed request | Upstream weather API failed. | Check ENVIROVISION_API_BASE_URL, ENVIROVISION_API_KEY, and network connectivity. |
| Map looks flat or uniform | Very low rainfall, or fewer than four sample points. | Check the hourly rainfall values in the response. |
| Repeated requests return instantly | Result cache hit. | Wait for TTL expiry or vary parameters slightly. |
Related files
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 asDEM_PATHand weather URLs.tests/test_hydro.pyandtests/test_api.py— automated checks.