# glofas-ewds > A small, typed Python library for GloFAS, the global river model of Copernicus, and the Copernicus fire danger indices, from the Early Warning Data Store (EWDS). It builds the requests, downloads the files, reads them on the right 0.05° cell, finds the river cell of a place, compares a discharge with the river's own history and with the official 2-, 5- and 20-year thresholds, says how far the model can be trusted on a river of that size, counts the ensemble members and the runs behind a forecast peak, and serves all of it as facts to a command line, an assistant and a page for a municipality. Source: https://agentengineering.it/glofas-ewds/ # glofas-ewds **Is this river high for *this* river?** GloFAS river discharge and the Copernicus Fire Weather Index from the Early Warning Data Store, read on the right grid cell. [![ci](https://github.com/agent-engineering-studio/glofas-ewds/actions/workflows/ci.yml/badge.svg)](https://github.com/agent-engineering-studio/glofas-ewds/actions/workflows/ci.yml) [![PyPI](https://img.shields.io/pypi/v/glofas-ewds)](https://pypi.org/project/glofas-ewds/) [![docs](https://img.shields.io/badge/docs-agentengineering.it-blue)](https://agentengineering.it/glofas-ewds/) ![python](https://img.shields.io/badge/python-3.12%20%7C%203.13-blue) ![mypy](https://img.shields.io/badge/mypy-strict-blue) ![coverage](https://img.shields.io/badge/coverage-99%25-brightgreen) [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/agent-engineering-studio/glofas-ewds/blob/main/LICENSE) ```python open_meteo_cell(8.43, 45.97) # (8.475, 45.975): the cell whose numbers you are really reading discharge_ratio(600.2, 181.9) # 3.3: the Toce's peak against its own ordinary high flow ``` A 7 by 7 grid of 0.05 degree GloFAS cells around the Toce near Candoglia, each labelled with its 90th percentile of daily discharge. The cell under the point reads 16 m³/s, the cell just west of it 147 m³/s, the row below 177 to 182 m³/s. One river, 49 cells. The 90th percentile of daily GloFAS 4 discharge in each 0.05° cell around the Toce near Candoglia, Nov 2024 to Oct 2026, from the public Open-Meteo flood API, on Open-Meteo's own coordinates. The red cell is the one under the point (16 m³/s); one cell west, 147 m³/s. Drawn by docs/make_images.py. - [What is it, in 30 seconds](#what-is-it-in-30-seconds) - [What it sees, and what it does not](#what-it-sees-and-what-it-does-not) - [Who is it for](#who-is-it-for) - [Try it in two minutes, with no account](#try-it-in-two-minutes-with-no-account) - [Run it locally](#run-it-locally) - [The page for a municipality](#the-page-for-a-municipality) - [Quick start with the EWDS](#quick-start-with-the-ewds) - [How it works](#how-it-works) - [How far to trust a river](#how-far-to-trust-a-river) - [What stands behind a forecast peak](#what-stands-behind-a-forecast-peak) - [For assistants: facts, not guesses](#for-assistants-facts-not-guesses) - [Recipes](#recipes) - [Notebooks](#notebooks) - [The traps we already fell into](#the-traps-we-already-fell-into) - [By source, not by hazard](#by-source-not-by-hazard) - [API at a glance](#api-at-a-glance) - [Data licence and credits](#data-licence-and-credits) ## What is it, in 30 seconds [GloFAS](https://global-flood.emergency.copernicus.eu/), the Global Flood Awareness System of Copernicus, models the discharge of every river on Earth on a 0.05° grid (about 5 km), every day, with a forecast for the days ahead. The [Early Warning Data Store](https://ewds.climate.copernicus.eu/) (EWDS) serves it as NetCDF grids, together with the Fire Weather Index Copernicus computes on ERA5. The data is free. Using it well is not: a cell too far west turns a river into a creek, a model version too new halves every number, and a recent month asked for the wrong way does not exist. This package holds the requests and the readers that get those right. | | What you get | |---|---| | 🎯 | **The right cell** for a point: `open_meteo_cell`, the same cell Open-Meteo serves, so a reference from the EWDS and a forecast from Open-Meteo describe the same water | | 📜 | **The requests, built for you**: GloFAS 4 history (consolidated, then intermediate), the 00 UTC control forecast, the six FWI components; split by month | | 📦 | **Downloads you can re-run**: one file per month or run, nothing asked twice, never half a file left behind | | 📈 | **Numbers per node**: daily series, forecast peaks, FWI components, for your own list of points | | 📏 | **A reference per river**: `references` and `discharge_ratio`, the forecast peak against the node's own ordinary high flow | | 🏞️ | **The river of a place**: `nearest_river` finds the cell that holds the river near a town, on the official 2-year flow of every cell | | ⚖️ | **How far to trust it**: `trust` gives a level per node, with the record of 41 known floods behind it | | 🗳️ | **What stands behind a forecast**: `credibility` counts the members and the runs that agree, as facts, with no verdict | | 🤖 | **Facts for assistants**: `Facts`, `ANSWER_RULES` and `check_text`: the numbers come from the data, a model may explain them, never invent them | | 🏛️ | **A page for a municipality**: the river, its history, the forecast and its return period, from data already on disk | | 🧪 | **Pure where it can be**: `import glofas_ewds` needs only numpy; `cdsapi` and `netCDF4` are extras | ## What it sees, and what it does not **GloFAS does not see flash floods, and this library cannot make it.** That is its headline limit, and it is measured. We took 41 Italian floods since 1997 and asked, on the river cell nearest each place: did the model reach its own official 2-year flow on the days of the flood? - **Floods from days of wide rain: 25 of 28.** The Po in 2000 at 1.98 times its 2-year flow, the Lamone at Faenza on 16 May 2023 at 3.31 times, on a small river. The three misses are near misses (0.85 to 0.96 of the level). - **Flash floods: 4 of 13.** The Misa at Senigallia, 15 September 2022: the model gives **0.4 m³/s on a cell whose 2-year flood is 33.4 m³/s**. The Magra at Aulla in 2011: 0.26 of the level. The Bisagno in Genoa, twice. The reason is in what the data is: the mean of a day, on a cell of about 5 km, from a model fed with rain on a much coarser grid. Six hours of storm on a basin of a few hundred km² are not in it. No threshold, ratio or percentile finds a flood that is not in the data. This is the **reanalysis**: the model run on the weather as it was later known, so it is the most the model can hold of an event. It is not a test of the forecasts issued in those days, which needs the archive of past forecasts and was not done. 41 floods are few, all Italian, three in the south: read the counts, not percentages. The whole table is in [the benchmark](https://agentengineering.it/glofas-ewds/benchmark/), and CI fails if the library quotes numbers the data do not give. ## Who is it for - Anyone who turns GloFAS into **alerts or scores**: a flood model, a dashboard, a newsroom map. A ratio to the river's own high flow is comparable between the Po and a torrent; a raw m³/s is not. - People who already read the **Open-Meteo flood API** and want the history in bulk from Copernicus instead of node by node, without the two disagreeing. - Fire-weather people checking **their own FWI** against the Copernicus one. It was extracted from [Limen](https://github.com/agent-engineering-studio/limen), the landslide, flood and wildfire monitor for Italy, where it fills the reference of 3,366 river nodes from about 25 monthly requests instead of about 52 calls per node to a public API capped at 10,000 calls a day. On 36,637 points (the whole 0.1° lattice of Italy plus 20,000 random ones) it picks the same cell as Limen's own code, and every request and reader gives identical results. ## Try it in two minutes, with no account ```bash pip install "glofas-ewds[netcdf]" glofas-ewds init --place "Faenza,11.88,44.29" # finds the river, downloads its data glofas-ewds facts faenza --about forecast ``` `init` downloads the three official threshold files once (about 520 MB, from ECMWF, no account), finds the river cell of the place on them, and asks the public Open-Meteo flood API for five years of history and the newest forecast with its 51 members. Everything goes to a **store** on disk (`$DATA_ROOT/glofas-ewds`, else `~/.cache/glofas-ewds`); every command after that reads the store, not the network. ```text $ glofas-ewds init --place "Faenza,11.88,44.29" --place "Senigallia,13.215,43.713" 2 places, 2 with a river; history for 2, forecast for 2 faenza: river cell 11.875, 44.275 at 1.7 km, 2-year flow 49.2 m³/s senigallia: river cell 13.175, 43.725 at 3.5 km, 2-year flow 33.4 m³/s ``` | Command | What it does | |---|---| | `glofas-ewds init --place "Name,lon,lat"` | find the river of each place and download its data (`--places file.csv` for many) | | `glofas-ewds update` | the newest forecast and the missing days, for every place: schedule this once a day | | `glofas-ewds places` | the places of the store and how old their data are | | `glofas-ewds facts faenza` | the facts of a place as JSON (`--about river`, `discharge`, `forecast`) | | `glofas-ewds find 11.88 44.29` | the river cell nearest a point and how far to trust it, storing nothing | | `glofas-ewds check text.md facts.json` | are all the numbers of a text in the facts? | | `glofas-ewds thresholds` | download the official threshold files only | `--source ewds` on `init` and `update` asks Copernicus itself instead of Open-Meteo: see [Quick start with the EWDS](#quick-start-with-the-ewds). ## Run it locally With Docker alone: ```bash git clone https://github.com/agent-engineering-studio/glofas-ewds cd glofas-ewds docker compose up # the demo, on http://localhost:3008 ``` The first `up` runs `init` once: it puts six places in the store (Faenza, Ferrara, Firenze, Roma, Senigallia, Gioia del Colle) and downloads their data from Open-Meteo, in a few seconds and with no key. | | Command | Where | |---|---|---| | The demo | `docker compose up` | | | Jupyter with the notebooks | `docker compose --profile notebooks up notebooks` | | | The newest forecast | `docker compose run --rm update` | | | The command line | `docker compose run --rm cli --help` | | | Python | `docker compose run --rm python` | | The containers have fixed names (`glofas-ewds-api`, `glofas-ewds-web`, `glofas-ewds-notebooks`), and the ports are chosen not to clash with the sister libraries; change them in `.env` (see `.env.example`). The data live in `./data/glofas-ewds`, or in `$DATA_ROOT/glofas-ewds` when you share a data root with other tools. Without Docker, with [uv](https://docs.astral.sh/uv/) and Node: ```bash make init # install everything, download the data of the demo make demo # the demo, on http://localhost:3008 make help # every target ``` ## The page for a municipality The page of the demo for Faenza, in Italian: a notice that this is model discharge and not an alert, how old the data are, a card on the river with a trust level of «scarsa» and the count of known floods, a card with the last discharge of 10.7 m³/s and a chart of the last year, a card with the forecast peak. `demo/web` is a page a public body can put on its own site: the river nearest the town, how far GloFAS can be trusted there, the last discharge against the river's own history, the forecast peak and its return period with the members and the runs behind it. In Italian and in English, built with Bootstrap Italia. - It reads **data already downloaded**: the EWDS needs an account and a queue of minutes, a public page cannot wait. So it says first how old its data are, and warns when they are old. - It opens on the place in `GLOFAS_EWDS_PLACE`, or on `?place=` in the address. Add your town with `glofas-ewds init --place "Name,lon,lat"` and refresh it with `glofas-ewds update` once a day. - It computes no number: everything it shows comes from `Facts`. - **It is not an alert service** and is not meant to become one: no flooded areas, no rain, no risk level. The alert is the bulletin of the civil protection, and the page says so on every screen. Before you publish it, put a reverse proxy with HTTPS in front of it: see [SECURITY.md](https://github.com/agent-engineering-studio/glofas-ewds/blob/main/SECURITY.md). ## Quick start with the EWDS The Early Warning Data Store is the source of record: Copernicus itself, the whole grid in one request, the reanalysis from 1979. ```bash pip install "glofas-ewds[ewds,netcdf]" ``` You need an [EWDS account](https://ewds.climate.copernicus.eu/) and its API key, in `CDSAPI_URL` / `CDSAPI_KEY` or `~/.cdsapirc`, and you must accept the licence of each dataset once on its page. ```python import asyncio from datetime import date from glofas_ewds import ( EwdsClient, discharge_ratio, discharge_series, forecast_peaks, references, ) NODES = [(8.43, 45.97), (11.88, 44.29), (11.25, 43.77)] # Toce, Lamone, Arno async def main() -> None: ewds = EwdsClient("data/ewds") start, end = date(2024, 11, 1), date(2026, 10, 31) history = await ewds.history(start, end) # 24 monthly files ref = references(discharge_series(history, NODES, start=start, end=end), p=0.9) latest = await ewds.latest_forecast() # today's run, or yesterday's if latest is not None: run, path = latest for node, peak in forecast_peaks(path, NODES).items(): print(run, node, round(peak), discharge_ratio(peak, ref[node])) asyncio.run(main()) ``` Each EWDS request waits in a queue, often for minutes; `EwdsClient` waits in a thread, so your event loop keeps serving. No live output is shown here: the releases were built without an EWDS key, and the readers are checked against synthetic files, against Limen's code and, every week, against the live EWDS (`live.yml`). ## How it works ```mermaid flowchart LR N["your nodes
(lon, lat)"] --> C["open_meteo_cell
the cell to read"] R["historical_request
forecast_request
fire_request"] --> Q["EWDS queue
(cdsapi)"] Q -->|"NetCDF, one per month / run"| D["download_*
.part, then rename"] D --> S["discharge_series
forecast_peaks
fire_values"] C --> S S --> P["references (p90)
discharge_ratio"] ``` Three panels of daily GloFAS 4 discharge from November 2024 to October 2026 with a dashed line at each river's 90th percentile: Toce at Candoglia 182 m³/s with a peak of 600, Lamone at Faenza 14 with a peak of 90, Arno at Florence 97 with a peak of 616. Three rivers, three scales. The dashed line is each river's own 90th percentile: the Lamone's 90 m³/s is 6.3 times its ordinary high flow, the Toce's 600 only 3.3. Real GloFAS 4 data via Open-Meteo, on the cell of the nine around each town with the largest mean flow. ## How far to trust a river A 0.05° cell is not a river, and a small stream is in no cell at all. `nearest_river` finds the cell that holds the river of a place; `trust` says how far the discharge of that cell can be trusted, by the **size of the river**: the official 2-year flow of its cell. ```python from glofas_ewds import local, trust files = local.download_thresholds(local.data_folder()) # 520 MB, once place = local.locate("Senigallia", 13.215, 43.713, files) place.river # River(cell=(13.175, 43.725), size=33.4, distance_km=3.5, ...) trust( place.river ) # Trust(level='poor', size='small', reasons=('small_river', 'other_cell'), seen=9, known=16) ``` | River size | 2-year flow | Level | Long rain: seen of known | Flash floods: seen of known | |---|---|---|---|---| | large | 300 m³/s and more | good | 16 of 18 | 0 of 1 | | medium | 100 to 300 m³/s | fair | 4 of 5 | 0 of 1 | | small | under 100 m³/s | poor | 5 of 5 | 4 of 11 | | none | no river cell within reach | none | | | A river cell more than 5 km from the place is never better than `fair`: it may be another river. `nearest_river` finds the **largest** river within 10 km, so Campi Bisenzio gets the Arno unless you pass a smaller radius. What the level cannot see: dams and diversions (two of the three near misses on long rain are the Tiber and the Adige, held back upstream while the model's thresholds are not), and a levee that breaks. The level is about the model, not about the danger. ## What stands behind a forecast peak One control run over a threshold is the weakest alarm there is. `credibility` adds what is already in the data: how many of the 51 members reach the 2-year flow, and how many runs in a row forecast it for the same days. ```python from glofas_ewds import credibility credibility(members, run, thresholds, previous=[(earlier_run, earlier_members), ...]) # Credibility(peak=162.7, peak_day=date(2023, 5, 16), years=20, level=49.2, # members=51, members_over=45, share=0.88, earlier_runs=2, runs_in_a_row=3) ``` It holds **facts, not a verdict**: no score, no level of alert. Holding an alarm back on three members out of 51 is the decision of whoever raises it. With no earlier run stored, `runs_in_a_row` is `None`: not known, which is not "the first run to say it". Nobody measured yet how often a peak with a given share of members is followed by a flood: that needs years of archived forecasts (`cems-glofas-reforecast`), and is the next step. ## For assistants: facts, not guesses The rule of every AI feature here: **the numbers come from the data; a model may explain them, never invent them.** - **`Facts`** answers with plain dictionaries: every number with the river cell it was read from, its source, when it was fetched and how many days old it is. `None` means not known, never "low". - **For an assistant or a tool server built on this package**: each method of `Facts` (`places`, `river`, `discharge`, `forecast`, `summary`, `check_text`) is one tool, read from the store with no network, and `ANSWER_RULES` is the text to give the model as its instructions. The package serves no protocol itself: ```python from glofas_ewds import ANSWER_RULES, Facts, Store from glofas_ewds.local import data_folder facts = Facts(Store(data_folder())) facts.forecast("faenza") facts.check_text("faenza", "A peak of 170 m³/s.") # {'place': 'faenza', 'not_in_the_facts': ['170'], 'faithful': False} ``` - **`check_text(text, facts)`** returns the numbers of a text that are in none of the facts: for an answer a model wrote, or a note someone rewrote. ```python check_text("The Lamone reached 180 m³/s, 3.3 times its high flow.", facts) # ['180', '3.3'] ``` - **The faithfulness set** (`benchmarks/faithful.py`, in CI) measures what the check lets through: of 15 faults written on purpose in hand-made answers, `check_text` finds the 10 that are invented or wrongly rounded and **none of the 5 that are swapped** (a real figure said of the wrong thing). No model wrote those answers: measuring one is the next step. - **For coding agents**: [`llms.txt`](https://agentengineering.it/glofas-ewds/llms.txt), [`llms-full.txt`](https://agentengineering.it/glofas-ewds/llms-full.txt) and the [agent skill](https://github.com/agent-engineering-studio/glofas-ewds/blob/main/skills/glofas-ewds/SKILL.md). ## Recipes **A reference without an account.** The pure parts work on any series: ```python from glofas_ewds import references references({"toce": series}, p=0.9, min_days=365) # None below a year of days ``` **Your own retry, budget or timeout.** Every download takes any object with `retrieve(dataset, request, target)`: ```python from glofas_ewds import cdsapi_client, download_history download_history(folder, start, end, client=MyQueueWithTimeout(cdsapi_client())) ``` **Another area.** Every request and download takes `area=(north, west, south, east)`; files for an area other than Italy carry the area in their name, so two areas can share a folder. **The official FWI next to yours.** ```python files = await ewds.fire(date(2025, 6, 1), date(2025, 9, 30)) fire_values(files, nodes) # {(node, day): {"fwi": ..., "ffmc": ..., "dc": ...}} ``` **How sure is the peak.** The control run is one future; the 50 perturbed members of the same run say how likely it is. Against the node's own reference: ```python path = await ewds.ensemble(run) # ~90 MB for Italy: pass a smaller area= if you can for node, members in ensemble_members(path, NODES).items(): # (member, lead time) print( node, exceedance_probability(members, ref[node]), # 0.62: 31 of 50 members exceedance_by_lead(members, ref[node]), ) # [0.0, 0.1, 0.62, ...]: when ``` **The 2-, 5-, 20-year flow.** The EWDS does not serve GloFAS's flood thresholds; fit them on the node's own reanalysis, which starts in 1979. These are your levels, by a Gumbel on annual maxima, not the official ones: ```python start, end = date(1980, 1, 1), date(2024, 12, 31) # 540 monthly files, once by_day = discharge_by_day(await ewds.history(start, end), NODES, start=start, end=end) levels = {n: return_levels(annual_maxima(d).values()) for n, d in by_day.items()} # {(11.88, 44.29): {2: ..., 5: ..., 20: ...}}; None below 20 complete years ``` ## Notebooks Four notebooks, saved with their results, in [`notebooks/`](https://github.com/agent-engineering-studio/glofas-ewds/tree/main/notebooks): the river of a town, the 41 floods we know, what stands behind a forecast peak, facts not guesses. `make notebooks` runs them again. ## The traps we already fell into 1. **Open-Meteo's numbers belong to the cell one step east.** Open-Meteo declares a cell for each point, but the values it returns are the ones the EWDS labels 0.05° further east: on 28 real nodes, 28 matched with the shift and 0 without it. On the Toce that is 2 m³/s against 22. Comparing the declared coordinates does not show it. `open_meteo_cell` applies the shift. 2. **The cell is picked in float32.** Open-Meteo rounds away from zero from an origin at -59.975 / -180.025 in single precision, so on the edge between two cells it goes up for some points and down for others. Doing it in float64 can pick the other neighbour. 3. **The cell next door is another river.** In the map above the cell under the point holds 16 m³/s and the one west of it 147. Never interpolate GloFAS between cells, and never trust a point without checking its cell. 4. **GloFAS 4, not 5.** Open-Meteo's forecast is GloFAS 4 (at Faenza on 11 October 2026: 7.1 / 6.1 / 8.9 m³/s from the EWDS against 7.3 / 5.9 / 8.9 from Open-Meteo); version 5 gives about half. A v4 forecast over a v5 reference is a number without meaning. The requests pin `version_4_0`. 5. **Recent months are "intermediate".** The consolidated history arrives months late (on 11 October 2026 it ended in June; intermediate reached 8 October). Asking a recent month as consolidated answers "not a valid combination"; the downloads then ask it as intermediate, and only for that error. 6. **`valid_time` is the end of the day.** The EWDS stamps a daily mean with the end of its 24 hours, the day after the one you asked for. `discharge_series` keys values by the day asked. 7. **Accept the licence first.** Every dataset has a licence to accept once on its EWDS page; until then each request answers 403, which looks like a bad key. That error is never turned into "intermediate". 8. **FWI variables have GRIB names.** In the fire NetCDF the variables are `fwinx`, `drtcode`, ..., not the names you asked for; `fire_values` finds them by `long_name`. The build-up index is "Fire buildup index" there. 9. **Mind the quotas.** The public Open-Meteo API caps at 10,000 calls a day, and two years of discharge cost about 52 calls per node. The EWDS gives the same history as a grid: two years of Italy are 24 or 25 monthly requests. 10. **Absent is not zero.** A node outside the file or on a masked cell (sea, no river network) gets no value. `discharge_ratio` returns `None` when it does not know how big the river is, never a reassuring 0. 11. **Open-Meteo's recent history is its forecast archive.** Its `consolidated_v4` model stops in 2024 (on 4 November 2026 it answered `null` for June 2025); after that the default `seamless_v4` series is `forecast_v4` day after day, not the reanalysis. At Faenza on 1 January 2025 that is 5.55 m³/s against 4.75 consolidated. A reference from the EWDS consolidated history and one from Open-Meteo's recent history are not the same series: compare them on consolidated days only. 12. **Open-Meteo's reanalysis starts in 1997.** On 28 November 2026 `consolidated_v4` answered nothing before 1 January 1997: the floods of November 1994 are not there. The EWDS has the reanalysis from 1979. 13. **The river of a town is not the largest cell nearby.** Within 10 km of Campi Bisenzio the largest cell is the Arno (2-year flow 349.9 m³/s), 5 km south; the Bisenzio is the cell under the town (32.4). `nearest_river` takes a radius, and `River.distance_km` says how far it went. These are measurements, each with its date, not promises from Copernicus or Open-Meteo. `tests/test_live.py` measures them again every week against the real services ([`live.yml`](https://github.com/agent-engineering-studio/glofas-ewds/blob/main/.github/workflows/live.yml)); a failure opens an issue whose assertion says which fact moved and what to change. ## By source, not by hazard This library is organised by **where the data comes from**, the Early Warning Data Store, not by the hazard it describes. So the Copernicus fire danger (`cems-fire-historical-v1`: `fire_request`, `download_fire`, `fire_values`) lives **here**, next to the river discharge, because it shares the EWDS requests, the monthly downloads and the cell arithmetic. Do not look for it in a wildfire library: [`fwi-chain`](https://github.com/agent-engineering-studio/fwi-chain) computes the Fire Weather Index from weather, with no dependency and no download; the official index to compare it with is here. ## API at a glance | Name | What it does | |---|---| | `open_meteo_cell(lon, lat)` / `declared_cell(lon, lat)` | the cell Open-Meteo serves / the one it declares | | `historical_request`, `forecast_request`, `fire_request`, `months` | the EWDS requests, without sending them | | `download_history`, `download_forecast`, `download_fire` | one NetCDF per month or run, re-runnable, with any `retrieve` client | | `EwdsClient(folder, *, url=None, key=None, retriever=None, area=ITALY)` | the same downloads, async, plus `latest_forecast()` | | `discharge_series`, `forecast_peaks`, `fire_values` | NetCDF to numbers per node (extra `netcdf`) | | `percentile`, `references`, `discharge_ratio` | a river's own reference, and how far above it a forecast is | | `download_ensemble`, `EwdsClient.ensemble`, `ensemble_members` | the 50 perturbed members, as (member, lead time) per node | | `exceedance_probability`, `exceedance_by_lead` | the share of members over a threshold, in all and per lead time | | `discharge_by_day`, `annual_maxima`, `return_levels` | the 2-, 5-, 20-year flow of a node, from its own reanalysis | | `threshold_url`, `read_threshold`, `flood_thresholds` | the official GloFAS v4 2-, 5-, 20-year thresholds of a node's cell, from ECMWF's public files | | `flood_label` | a forecast peak as "above the 5-year flood", with the day of the peak | | `forecast_peak_days`, `peak_day` | the day a forecast peaks, per node | | `reference_before`, `peak_ratios` | a replay: the reference from the days before a window, and the ratio a forecast would have given each day | | `nearest_river(sizes, lon, lat, radius_km=10)`, `threshold_window` | the river cell of a place, and the cells around a point to look in | | `trust(river)`, `KNOWN_FLOODS` | how far to trust a node, and the record of known floods behind each level | | `credibility(members, run, thresholds, previous=())` | members and runs behind a forecast peak, as facts | | `Store`, `Place`, `local.locate`, `local.fill_from_open_meteo`, `local.fill_from_ewds_files` | places on disk, and what fills them | | `Facts(store)` `.places()` `.river()` `.discharge()` `.forecast()` `.summary()` | the numbers an assistant or a page may quote, with source and age | | `check_text(text, facts)` | the numbers of a text that are not in the facts | | `openmeteo.flood_url`, `parse_daily`, `parse_members`, `fetch` | the same GloFAS 4 numbers from Open-Meteo, with no key | | `point_for_cell(cell)`, `distance_km(a, b)` | the node that reads a cell; kilometres between two points | | `candidate_runs(today, latest_saved=None)` | the forecast runs worth trying, newest first | | `GlofasEwdsError` | the package's exception | The full reference is on the [documentation site](https://agentengineering.it/glofas-ewds/). ## Development ```bash uv sync make help # every target make check # ruff, mypy --strict, pytest with coverage, the two benchmarks make docs # the documentation site, llms.txt and llms-full.txt uv run python -m benchmarks.floods # the 41 floods, as a table uv run python -m benchmarks.faithful score uv run --group docs python docs/make_images.py # the README figures GLOFAS_EWDS_LIVE=1 CDSAPI_KEY=... uv run --extra ewds pytest -m live --no-cov # the traps, live ``` ## Data licence and credits - **GloFAS (CEMS-Floods).** Under the [CEMS-FLOODS datasets licence](https://ewds.climate.copernicus.eu/licences/cems-floods). If you publish data derived from it, say so with a notice such as *"Contains modified Copernicus Emergency Management Service information [Year]"*. The data is provided for information only: **a ratio computed with this package is not a flood warning**, and must not be presented as one. Official warnings come from your national and regional services. - **Fire danger (`cems-fire-historical-v1`).** © Copernicus Emergency Management Service, under the licence stated on its EWDS page, to be accepted once there. - **The official thresholds** are the GloFAS v4 flood thresholds ECMWF publishes as [CEMS auxiliary data](https://confluence.ecmwf.int/display/CEMS/Auxiliary+Data). - **Open-Meteo** is a third party. Its [flood API](https://open-meteo.com/en/docs/flood-api) serves the same GloFAS 4 numbers under its own terms and attribution ([CC BY 4.0](https://open-meteo.com/en/license), free for non-commercial use, 10,000 calls a day): the default source of `glofas-ewds init`, of the demo, of the notebooks, of the benchmark and of the figures. The equality with the EWDS is checked every week (`live.yml`); its reanalysis starts in 1997, and after 2024 its history is its archive of forecasts. **The EWDS stays the source of record**: use `--source ewds` for anything you publish. Contains modified Copernicus Emergency Management Service information 2026. This package is not affiliated with Copernicus, ECMWF, the JRC or Open-Meteo. Code under [Apache-2.0](https://github.com/agent-engineering-studio/glofas-ewds/blob/main/LICENSE). # Examples: notebooks and the demo ## Notebooks Four notebooks tell what the library does, each saved **with its results**: read it like an article, or run it. They are in [`notebooks/`](https://github.com/agent-engineering-studio/glofas-ewds/tree/main/notebooks). | | Notebook | What it shows | Data | |---|---|---|---| | 1 | [The river of a town](https://github.com/agent-engineering-studio/glofas-ewds/blob/main/notebooks/01_the_river_of_a_town.ipynb) | The Lamone at Faenza: its river cell, five years of history, the forecast with its 51 members. | live: Open-Meteo, no key | | 2 | [The floods we know](https://github.com/agent-engineering-studio/glofas-ewds/blob/main/notebooks/02_the_floods_we_know.ipynb) | 41 Italian floods: which ones the model holds, and the flash floods it does not. | offline: `benchmarks/floods.json` | | 3 | [What stands behind a forecast peak](https://github.com/agent-engineering-studio/glofas-ewds/blob/main/notebooks/03_behind_a_forecast.ipynb) | Members and runs behind a peak, as facts; "not known" is not zero. | live for today; a replay for May 2023 | | 4 | [Facts, not guesses](https://github.com/agent-engineering-studio/glofas-ewds/blob/main/notebooks/04_facts_not_guesses.ipynb) | The facts, `check_text`, and what the check cannot see. | offline: `benchmarks/faithful.json` | ```bash uv sync --group examples uv run --group examples jupyter lab notebooks make notebooks # run them all again and save the results docker compose --profile notebooks up notebooks # the same in Docker, on http://localhost:8886 ``` ## The demo A page for a municipality: the river of a place, its history, the forecast and its return period, from data already on disk. ```bash docker compose up # http://localhost:3008 make demo # the same without Docker (uv and Node) ``` It opens on `GLOFAS_EWDS_PLACE` (default `faenza`), or on `?place=` in the address; `?lang=en` is English. Its API is `demo/api.py`: three URLs over [`Facts`](api/facts.md), reading the store and never the network. ## Facts for an assistant ```bash glofas-ewds init --place "Faenza,11.88,44.29" # once ``` ```python from glofas_ewds import ANSWER_RULES, Facts, Store from glofas_ewds.local import data_folder facts = Facts(Store(data_folder())) facts.summary("faenza") # the facts, with their source and their age facts.check_text("faenza", "The peak is 180 m³/s.") # the numbers not in the facts ``` The package serves no protocol: an assistant, or a tool server, built on it exposes each method of `Facts` as a tool and gives the model `ANSWER_RULES` as its instructions. See [Facts](api/facts.md). # The benchmark: 41 floods we know Does GloFAS hold the floods we remember? This page is the answer, with every flood listed. It is what [`trust`](api/trust.md) quotes, and CI fails if the library and this table disagree. ## The question For each flood: on the river cell nearest the place ([`nearest_river`](api/rivers.md)), did the GloFAS 4 discharge reach the **official 2-year flow of that cell** on one of the days of the flood? If it did, the flood is *seen*: an alert built on the model's own thresholds had something to fire on. If it did not, no threshold, ratio or percentile can find it, because it is not in the data. ## What it measures, and what it does not - The discharge is the **reanalysis**: the model run on the weather as it was later known. It is the most the model can hold of an event, so a flood missing here is missing for good. - It is **not a test of the forecasts** issued in those days. That needs the archive of past forecasts (`cems-glofas-reforecast`, an EWDS account and hours of queue) and was not done. A flood seen here may still have been forecast late, or not at all. - The floods are 41, all Italian, since 1997 (Open-Meteo's reanalysis starts there), and only three are in the south. Read the counts, not percentages. - "Long" and "flash" are our labels, from the chronicle of each event: days of wide rain, or a storm of a few hours. - The 2-year flow is the model's own threshold. On a river held back by dams (the Tiber, the Adige) the model does not know about the dams. ## The result | Flood | Kind | River size | 2-year flow | Peak in the model | Peak / 2-year | Seen | |---|---|---|---:|---:|---:|---| | Po at Pontelagoscuro | long | large | 5211.4 | 10326.6 on 2000-10-17 | 1.98 | yes | | Po at Pontelagoscuro | long | large | 5211.4 | 7924.0 on 2009-04-30 | 1.52 | yes | | Po at Pontelagoscuro | long | large | 5211.4 | 8259.4 on 2014-11-18 | 1.58 | yes | | Po at Pontelagoscuro | long | large | 5211.4 | 9140.1 on 2019-11-26 | 1.75 | yes | | Dora Baltea at Ivrea | long | large | 440.8 | 828.9 on 2000-10-15 | 1.88 | yes | | Tanaro at Alessandria | long | large | 422.1 | 1136.6 on 2016-11-25 | 2.69 | yes | | Tevere at Roma | long | large | 2612.2 | 2248.1 on 2008-12-12 | 0.86 | no | | Tevere at Roma | long | large | 2612.2 | 2896.3 on 2012-11-12 | 1.11 | yes | | Arno at Pisa | long | large | 663.1 | 1015.2 on 2014-01-31 | 1.53 | yes | | Arno at Pisa | long | large | 663.1 | 1060.7 on 2019-11-17 | 1.60 | yes | | Ombrone at Istia d'Ombrone | long | large | 494.3 | 1195.7 on 2012-11-12 | 2.42 | yes | | Serchio at Vecchiano | long | medium | 240.1 | 413.0 on 2009-12-24 | 1.72 | yes | | Adige at Trento | long | large | 417.4 | 355.4 on 2018-10-30 | 0.85 | no | | Piave at Ponte di Piave | long | large | 334.8 | 448.8 on 2018-10-30 | 1.34 | yes | | Brenta at Bassano del Grappa | long | large | 314.0 | 740.3 on 2018-10-29 | 2.36 | yes | | Tagliamento at Latisana | long | large | 736.2 | 1573.0 on 2018-10-29 | 2.14 | yes | | Bacchiglione at Vicenza | long | medium | 111.3 | 170.8 on 2010-11-01 | 1.53 | yes | | Toce at Candoglia | long | large | 404.5 | 556.2 on 2020-10-03 | 1.38 | yes | | Sesia at Vercelli | long | large | 511.6 | 750.6 on 2020-10-03 | 1.47 | yes | | Secchia at Bastiglia | long | medium | 153.0 | 197.2 on 2014-01-18 | 1.29 | yes | | Panaro at Nonantola | long | medium | 117.0 | 112.5 on 2020-12-06 | 0.96 | no | | Reno at Casalecchio di Reno | long | small | 97.2 | 107.9 on 2019-02-02 | 1.11 | yes | | Pescara at Pescara | long | medium | 178.5 | 278.9 on 2013-12-02 | 1.56 | yes | | Bradano at Metaponto | long | large | 322.5 | 603.0 on 2011-03-02 | 1.87 | yes | | Lamone at Faenza | long | small | 49.2 | 102.3 on 2023-05-02 | 2.08 | yes | | Lamone at Faenza | long | small | 49.2 | 162.7 on 2023-05-16 | 3.31 | yes | | Lamone at Faenza | long | small | 49.2 | 63.3 on 2024-09-19 | 1.29 | yes | | Savio at Cesena | long | small | 56.2 | 165.0 on 2023-05-17 | 2.93 | yes | | Calore at Benevento | flash | large | 479.7 | 248.5 on 2015-10-15 | 0.52 | no | | Idice at Budrio | flash | small | 43.2 | 68.0 on 2024-10-19 | 1.57 | yes | | Misa at Senigallia | flash | small | 33.4 | 41.2 on 2014-05-03 | 1.23 | yes | | Misa at Senigallia | flash | small | 33.4 | 0.4 on 2022-09-17 | 0.01 | no | | Magra at Aulla | flash | medium | 113.3 | 29.1 on 2011-10-25 | 0.26 | no | | Entella at Chiavari | flash | small | 41.7 | 47.5 on 2014-11-11 | 1.14 | yes | | Bisagno at Genova | flash | small | 13.4 | 10.3 on 2011-11-05 | 0.77 | no | | Bisagno at Genova | flash | small | 13.4 | 8.1 on 2014-10-10 | 0.61 | no | | Baganza at Parma | flash | small | 69.9 | 24.5 on 2014-10-14 | 0.35 | no | | Bisenzio at Campi Bisenzio | flash | small | 32.4 | 34.4 on 2023-11-02 | 1.06 | yes | | Seveso at Milano Niguarda | flash | small | 75.9 | 42.5 on 2014-07-08 | 0.56 | no | | Cedrino at Galtellì | flash | small | 91.3 | 70.6 on 2013-11-18 | 0.77 | no | | Rio Ardenza at Livorno | flash | small | 4.5 | 3.7 on 2017-09-10 | 0.81 | no | | River size | Long rain: seen of known | Flash floods: seen of known | |---|---|---| | large | 16 of 18 | 0 of 1 | | medium | 4 of 5 | 0 of 1 | | small | 5 of 5 | 4 of 11 | | none | - | - | | all | 25 of 28 | 4 of 13 | The headline: **25 of 28 floods from long rain, 4 of 13 flash floods.** The lowest of all is the Misa at Senigallia on 15 September 2022: 0.4 m³/s on a cell whose 2-year flood is 33.4 m³/s. The same cell holds the flood of 3 May 2014 (41.2 m³/s, 1.23 times the level): the river is in the model, that storm was not. ## Run it ```bash uv run python -m benchmarks.floods # this table: no key, no network uv run python -m benchmarks.floods --check # what CI runs uv run python -m benchmarks.fetch # record the data again (network, 520 MB of thresholds) ``` The data are in `benchmarks/floods.json`: for every flood the river cell, its three official thresholds and the daily discharge from ten days before to ten days after. The list is `benchmarks/floods.toml`; add a flood there, run `fetch`, then `floods --write`, and update `KNOWN_FLOODS` in `glofas_ewds.trust`: `--check` will tell you the numbers to write. ## The faithfulness set A second benchmark is about words, not rivers: how faithfully a text quotes the facts. Five questions with real facts, two hand-written answers each (one faithful, one with faults written on purpose), every number labelled with the fact it is said of. ```bash uv run python -m benchmarks.faithful score ``` Of the 15 faults, [`check_text`](api/text.md) finds the 10 numbers that are invented or wrongly rounded, and none of the 5 that are swapped: a real figure of the facts said of the wrong thing. No model wrote these answers; asking a model, and a second one to label what it wrote, is the next step. Discharge: GloFAS, Copernicus Emergency Management Service, served by Open-Meteo. Thresholds: GloFAS v4 flood thresholds, ECMWF. # Cells ## `glofas_ewds.cells` Which GloFAS cell a point reads, and where that cell is in a file. Pure: nothing here does I/O. GloFAS 4 is a regular grid of 0.05° (about 5 km) cells. Along a river two neighbouring cells can differ by an order of magnitude: one holds the main channel, the next a side valley. Picking the wrong one is the most expensive mistake you can make with this data, and nothing raises when you make it. Two facts, both measured on 11 October 2026 on 28 real nodes in Italy: * Open-Meteo picks the cell for a point in **float32**, rounding **away from zero** from an origin at -59.975 / -180.025. On the edge between two cells this goes up for some points and down for others. * The values Open-Meteo returns for that cell are the ones the EWDS labels **one step east**. With the shift, 28 nodes out of 28 match the EWDS (consolidated history and forecast alike); without it, 0 out of 28. On the Toce that is 2 m³/s against 22. Comparing the coordinates Open-Meteo *declares* does not show it. `open_meteo_cell` gives the EWDS cell whose numbers Open-Meteo serves for a point, so a reference computed from the EWDS and a forecast read from Open-Meteo talk about the same water. ### `declared_cell(longitude: float, latitude: float) -> Node` The cell Open-Meteo *declares* in its answer for a point. This is not the cell whose values it returns: see `open_meteo_cell`. ### `open_meteo_cell(longitude: float, latitude: float) -> Node` The EWDS cell (lon, lat) whose values Open-Meteo returns for a point. The declared cell moved one step east. ### `cell_indices(latitudes: npt.ArrayLike, longitudes: npt.ArrayLike, cells: Sequence[Node], *, step: float = GRID_STEP) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp], npt.NDArray[np.bool_]]` Row, column and "inside the file" for each cell, on a file's axes. Outside the area you downloaded the nearest point is the edge, which is not the cell: those come back with `inside` False. ### `point_for_cell(cell: Node) -> Node` A point for which `open_meteo_cell` gives `cell`: its centre, one step west. The way back from a cell you found on a grid (a river, in a threshold file) to a node every reader of this package, and Open-Meteo, reads there. ### `distance_km(a: Node, b: Node) -> float` Kilometres between two (lon, lat) points on a sphere of 6,371 km. # Rivers ## `glofas_ewds.rivers` The river nearest a place, on a grid where a cell is not a river. Pure: nothing here does I/O. A town is a point; its river is somewhere in the 0.05° cells around it, and the cell under the town hall is usually not it. On the Toce near Candoglia the cell under the point carries 16 m³/s and the next one 147. `nearest_river` takes the size of every cell around a place (the 2-year flow of the official thresholds, `glofas_ewds.thresholds.threshold_window`, or your own reference per cell) and says which cell holds the river, how far it is and how it compares with the cell of the place itself. It finds the **largest** river within the radius, at its nearest cell. A town on a tributary five kilometres from the Po gets the Po: read `distance_km` and `own_size` before you trust the choice, and pass a smaller radius when you know better. ### `class River(cell: Node, size: float, distance_km: float, own_cell: Node, own_size: float | None)` The cell that holds the river of a place. #### `River.moved: bool` Is the river in another cell than the one the place reads? ### `nearest_river(sizes: Mapping[Node, float], longitude: float, latitude: float, *, radius_km: float = RIVER_RADIUS_KM, share: float = RIVER_SHARE) -> River | None` The nearest cell of the largest river within `radius_km` of a place. `sizes` is `{cell centre: m³/s}` for the cells around the place. `None` when no cell in the radius has a positive size: there is no river here that GloFAS models, which is not "the river is low". # Trust ## `glofas_ewds.trust` How far the discharge of a node can be trusted, before you look at it. Pure: nothing here does I/O. GloFAS is a model of the rivers of the world on 0.05° cells (about 5 km), fed with rain on a much coarser grid, and what it gives is the mean of a day. Two things follow, and neither raises an error: * **A cell is not a river.** The river of a place is in one of the cells around it, and a small stream is in none: the model has no channel there. * **A day is not a flood.** A flood that rises and falls in six hours on a basin of a few hundred km² is a small bump in a daily mean, when the rain that caused it is in the model at all. `trust` turns what is known about a node (its river cell, from `glofas_ewds.rivers.nearest_river`) into a level and its reasons. The levels are by the **size of the river**: the official 2-year flow of its cell. `KNOWN_FLOODS` is the record behind them: 41 Italian floods since 1997, and whether GloFAS reached its own 2-year level on the days of the flood (`benchmarks/floods.py`, checked in CI; the benchmark fails if these numbers and its results differ). It is a record of the **reanalysis**: what the model holds of each flood once the weather is known, not what was forecast before. What this cannot see: dams and diversions (the Tiber and the Adige are held back upstream, and the model's thresholds are not), and a levee that breaks. A level is about the model, not about the danger. ### `class Trust(level: str, size: str, reasons: tuple[str, ...], seen: int, known: int)` How far to trust the discharge of a node. ### `size_class(size: float | None) -> str` `large`, `medium`, `small` or `none` for a 2-year flow in m³/s. ### `trust(river: River | None) -> Trust` The trust of a node whose river is `river` (`None`: no river found). The level is the size of the river; a river cell more than `FAR_KM` from the place is never better than `fair`. # Behind a forecast ## `glofas_ewds.credibility` What stands behind a forecast peak: members and runs, as facts. Pure: nothing here does I/O. One control run over a threshold is the weakest alarm there is, and it is what a discharge ratio alone fires on. Two more things are already in the data and cost nothing: * **the ensemble**: 51 forecasts of the same run. Three of them over the 2-year flood and forty of them over it are the same control run and very different news; * **the runs before**: a peak that yesterday's and the day before's runs already forecast for the same days is not a peak that appeared this morning. `credibility` puts them in one record. It holds **facts, not a verdict**: no score, no level of alert. Whether three members out of 51 are enough to hold an alarm back is the decision of whoever raises the alarm, and nobody measured here how often a peak with a given share is followed by a flood: that needs years of archived forecasts (`cems-glofas-reforecast`). Read it next to `glofas_ewds.trust.trust`, which says what GloFAS saw of the known floods on rivers of that size. ### `class Credibility(peak: float, peak_day: date, years: int | None, level: float, members: int, members_over: int, share: float, earlier_runs: int, runs_in_a_row: int | None)` A forecast peak, and how many forecasts stand behind it. ### `credibility(members: npt.ArrayLike, run: date, thresholds: Mapping[int, float | None], *, previous: Sequence[tuple[date, npt.ArrayLike]] = ()) -> Credibility | None` What stands behind the forecast of `run`. `members` is (member, lead time) with the control run first, as `glofas_ewds.glofas.ensemble_members` and `glofas_ewds.openmeteo.parse_members` give it. `thresholds` is `{years: m³/s}` for the same cell. `previous` is earlier runs of the same node, `(run, members)`, in any order; runs that are not earlier are ignored. `None` when there is nothing to count against: no 2-year threshold, or a control run that is all masked. "I don't know" is not "no alarm". # Facts ## `glofas_ewds.facts` The numbers an assistant, or a page, may quote: each with its source and its age. No network: everything is read from a `glofas_ewds.store.Store`. Ask a language model "is the Lamone high?" and it answers with a number, whether it has one or not. `Facts` gives it the number. Every answer is a plain dictionary, ready for JSON, that says which river cell it was read from, where the data came from, when it was fetched and how many days old it is, and how far GloFAS can be trusted on a river of that size. The model words the answer; it does not compute it. This is what the command line and the demo serve, and what an assistant or a tool server built on this package should call:: facts = Facts(Store("data/glofas-ewds")) facts.forecast("faenza") * `Facts.places`: the places of the store, and how old their data are. * `Facts.river`: the river cell of a place, and how far to trust it. * `Facts.discharge`: the last day of discharge against the place's own history. * `Facts.forecast`: the forecast peak, its return period, and what stands behind it. * `Facts.summary`: all three, for one place. * `Facts.check_text`: the numbers of a text that are in none of the facts of a place. `ANSWER_RULES` is the same rules written for whoever words an answer from these facts: give it to the model as its instructions. The rules every answer follows: * `None` means not known, which is never "low" and never "no flood". A return period of `None` is "below the 2-year flow" only when `below_two_year_flow` is true; otherwise it could not be computed; * m³/s are rounded to 0.1 and shares to 0.01: the model does not know more; * a forecast is labelled as a forecast, with its run; * nothing here is an alert. The alert is the bulletin of the civil protection. ### `ANSWER_RULES: Final[str]` The rules for whoever words an answer from `Facts`. Meant for whoever builds an assistant, or a tool server, on the functions of this package: pass it to the model as its instructions (the system prompt, or the instructions of the server), and expose each method of `Facts` as a tool of the same name. ### `class Facts(store: Store, *, today: date | None = None)` Answers about the places of a store, as dictionaries of facts. #### `Facts.today: date` The day ages are counted from (UTC), unless one was given. #### `Facts.places() -> dict[str, Any]` The places of the store: where, whether a river was found, how old the data are. #### `Facts.river(place_id: str) -> dict[str, Any]` The river cell of a place, its official thresholds, and how far to trust it. #### `Facts.river_of(place: Place) -> dict[str, Any]` `river` for a place that is not in the store (`glofas_ewds.local.locate`). #### `Facts.discharge(place_id: str) -> dict[str, Any]` The last day of discharge of a place's river, against its own history. #### `Facts.forecast(place_id: str) -> dict[str, Any]` The forecast peak of a place's river, its return period and what stands behind it. #### `Facts.summary(place_id: str) -> dict[str, Any]` Everything about one place: its river, the last discharge, the forecast. #### `Facts.check_text(place_id: str, text: str) -> dict[str, Any]` Check a text written about a place against all the facts of that place. The numbers of `text` that are in none of the facts of `summary` (see `glofas_ewds.text.check_text` for how a number is matched). `faithful` is true when every number is a fact:: {"place": "faenza", "not_in_the_facts": ["170"], "faithful": False} Raises `glofas_ewds.errors.GlofasEwdsError` when the store has no such place. # Checking a text ## `glofas_ewds.text` Is every number of a text in the facts it was written from? Pure: nothing here does I/O. The rule of every AI feature of this package: the numbers come from the data, a model may explain them, never invent them. `check_text` is the part of the rule a program can enforce. Give it a text (a model's answer, a press note, a paragraph someone rewrote) and the facts it was written from, and it returns the numbers of the text that are in none of the facts. It catches a number that is not there. It does not catch a number said of the wrong thing ("the peak is 112.1" when 112.1 is the 20-year threshold): the figure exists, the sentence is wrong. `benchmarks/faithful.py` measures how often that happens. ### `numbers(text: str) -> list[str]` The numbers of a text, as written and in order. `3,510` is one number (a comma between groups of three digits is a thousands separator), `2nd` is 2, `2026-11-28` is three numbers, and digits inside a word (`v4`) are not a number. ### `figures(value: Any) -> Iterator[float]` Every number in a tree of facts: values, keys, and the numbers inside strings. Digits glued to a letter are part of a name, not a number: `peak_m3s` and `seamless_v4` hold none. A time stamp counts by its parts. ### `check_text(text: str, facts: Any) -> list[str]` The numbers of `text` that are not in `facts`, as written (empty: all found). A number of the text is found when a figure of the facts, rounded to the decimals the text uses, is that number: `163` and `162.7` both match 162.68, `160` does not. Dates count by their parts (`16 May 2023` matches `2023-05-16`). Percentages are not converted: a share of 0.61 is found as `0.61`, not as `61`, so give the facts the figure you want quoted. # Command line ## `glofas_ewds.cli` The `glofas-ewds` command. * `glofas-ewds thresholds`: download the official GloFAS v4 threshold files (three files, about 520 MB, once; no account). * `glofas-ewds init --place "Faenza,11.88,44.29"`: find the river of each place, read its thresholds, download its history and forecast, and write the place to the store. `--places file.csv` reads `name,lon,lat[,radius_km]` lines. Safe to run again: it adds what is missing. * `glofas-ewds update`: the newest forecast, and the days of history since the last one, for every place of the store. This is what to schedule. * `glofas-ewds places`: the places of the store and how old their data are. * `glofas-ewds facts faenza`: the facts of a place as JSON (`--about river`, `discharge`, `forecast` or `summary`). * `glofas-ewds find 11.88 44.29`: the river cell nearest a point, its thresholds and how far to trust it, without storing anything. * `glofas-ewds check text.md facts.json`: are all the numbers of a text in the facts? For a text written, or rewritten, by someone else. `--source open-meteo` (the default) needs no key. `--source ewds` asks Copernicus itself: it needs the `ewds` extra, an EWDS key (`~/.cdsapirc` or `CDSAPI_URL` and `CDSAPI_KEY`) with the GloFAS licences accepted, and minutes of queue. The store is `--data`, else `$DATA_ROOT/glofas-ewds`, else `~/.cache/glofas-ewds`. ### `main(argv: Sequence[str] | None = None) -> int` Run the command; 0 when it worked, 1 when the library refused, 2 on a bad argument. # Store ## `glofas_ewds.store` Places and their rivers, kept on disk: what the facts and the UI read. Pure Python and JSON: no network, no NetCDF. The EWDS needs an account and a queue of minutes, and a public page cannot wait minutes. So everything that answers a question reads a **store**: a folder with one JSON file per place, filled beforehand (`glofas-ewds init`, `glofas-ewds update`) and read as it is. Every piece of data in it carries where it came from and when it was fetched, so an answer can say how old it is. A `Place` holds a town, the river cell found for it (`glofas_ewds.rivers.nearest_river`), the official thresholds of that cell, the daily history and the last forecast runs, newest last. ### `stamp(time: datetime) -> str` A time as the store writes it: `2026-11-28T15:04Z`, always UTC. ### `slug(name: str) -> str` A file-safe id from a name: `Campi Bisenzio` gives `campi-bisenzio`. ### `class Run(run: date, members: tuple[tuple[float | None, ...], ...], source: str, fetched: str)` One forecast run of a node: (member, lead time), the control run first. ### `class Place(id: str, name: str, lon: float, lat: float, river: River | None = None, thresholds: dict[int, float | None] = dict(), thresholds_source: str | None = None, history: dict[date, float] = dict(), history_source: str | None = None, history_fetched: str | None = None, runs: list[Run] = list())` A place, its river and what was downloaded for it. #### `Place.node: Node | None` The point to give every reader for this river; `None` without a river. #### `Place.add_run(run: Run) -> None` Keep `run`, replacing one of the same day; drop the oldest past `MAX_RUNS`. ### `to_json(place: Place) -> dict[str, Any]` A place as plain JSON types. ### `from_json(data: dict[str, Any]) -> Place` A place from what `to_json` wrote. ### `class Store(folder: Path | str)` The places of a data folder, one JSON file each under `places/`. #### `Store.ids() -> list[str]` The ids of the places in the store, sorted. #### `Store.load(place_id: str) -> Place` The place `place_id`; `glofas_ewds.errors.GlofasEwdsError` if unknown. #### `Store.places() -> list[Place]` Every place of the store. #### `Store.save(place: Place) -> Path` Write `place`; never half a file (`.part`, then rename). #### `Store.nearest(longitude: float, latitude: float) -> tuple[Place, float] | None` The stored place nearest a point, and its distance in km; `None` if empty. # Filling the store ## `glofas_ewds.local` Fill the store: find the river of a place, download its thresholds, history and forecast. This is where the I/O of the store is. Reading the threshold files and the EWDS files needs the `netcdf` extra; the EWDS downloads need the `ewds` extra and an account; Open-Meteo needs neither. * `data_folder`: where the library keeps its data. * `download_thresholds`: the three official threshold files (about 520 MB, once), from ECMWF, with no account. * `locate`: a place, its river cell and the thresholds of that cell. * `fill_from_open_meteo`: history and forecast of every place, with no key. * `fill_from_ewds_files`: the same from EWDS files you downloaded (`glofas_ewds.client.EwdsClient`): the source of record. Two sources, one store. Open-Meteo is a third party that serves the same GloFAS 4 numbers (checked against the EWDS every week, `live.yml`), under its own terms and attribution; its reanalysis starts on 1 January 1997, and after 2024 its history is its archive of forecasts. The EWDS is Copernicus itself, from 1979, and is what to use for anything you publish. ### `data_folder(folder: Path | str | None = None) -> Path` Where the data of this library are: `folder`, else `$DATA_ROOT/glofas-ewds`, else `~/.cache/glofas-ewds`. ### `threshold_files(folder: Path, periods: Sequence[int] = RETURN_PERIODS) -> dict[int, Path]` Where the threshold file of each return period is kept under `folder`. ### `download_thresholds(folder: Path, periods: Sequence[int] = RETURN_PERIODS, *, opener: Callable[[str], Any] | None = None) -> dict[int, Path]` The official threshold files under `folder`; one already there is not asked again. About 173 MB each. `opener` opens a URL as a readable stream (default: `urllib`); a download that fails leaves no file behind. ### `locate(name: str, longitude: float, latitude: float, files: Mapping[int, Path], *, radius_km: float = RIVER_RADIUS_KM, place_id: str | None = None) -> Place` A place with its river cell and the official thresholds of that cell. The river is looked for on the file of the shortest return period (the 2-year flow). A place with no river within `radius_km` is returned without one: GloFAS models nothing there. ### `add_history(places: Sequence[Place], by_node: Mapping[Node, Mapping[date, float]], *, source: str, now: datetime | None = None) -> int` Merge daily values into the history of the places that read each node. Returns how many places got at least one day. ### `add_runs(places: Sequence[Place], by_node: Mapping[Node, tuple[date, Sequence[Sequence[float]]]], *, source: str, now: datetime | None = None) -> int` Add a forecast run, `(run, members)`, to the places that read each node. NaN in `members` is stored as `null`. Returns how many places got one. ### `fill_from_open_meteo(places: Sequence[Place], *, today: date | None = None, years: float = HISTORY_YEARS, history: bool = True, forecast_days: int = FORECAST_DAYS, fetch: Fetch = openmeteo.fetch, now: datetime | None = None) -> dict[str, int]` History and forecast of every place with a river, from Open-Meteo. No key. The history goes from `years` ago (never before 1 January 1997) to yesterday; a place that already has days is asked only for what is after its last one. Returns `{"history": places, "forecast": places}` filled. ### `fill_from_ewds_files(places: Sequence[Place], *, history: Iterable[Path] = (), start: date | None = None, end: date | None = None, run: date | None = None, forecast: Sequence[Path] = (), now: datetime | None = None) -> dict[str, int]` History and forecast of every place with a river, from EWDS files. `history` are the files of `glofas_ewds.download.download_history` for `start` to `end`. `forecast` are the files of one `run`: the control run first, then (optionally) its ensemble. Needs the `netcdf` extra. ### `save_all(store: Store, places: Sequence[Place]) -> list[Path]` Write every place to the store. # Open-Meteo ## `glofas_ewds.openmeteo` The same GloFAS 4 numbers from Open-Meteo, for whoever has no EWDS account. The EWDS needs an account, a licence accepted per dataset and a queue of minutes. The `Open-Meteo flood API `_ serves the same GloFAS 4 discharge with no key, point by point: the cell `glofas_ewds.cells.open_meteo_cell` names is the one whose values it returns (28 nodes out of 28 on 11 October 2026, and again every week in `live.yml`). This module asks it with the standard library alone. It is the small door, not the main one: a few nodes, a few years. The public API counts a call for every two weeks of every point (a node's two years are about 52 calls) and caps a day at 10,000; for Italy in bulk, use the EWDS. After 2024 its history is its forecast archive, not the reanalysis. The builders and the parsers are pure; `fetch` is the only I/O. ### `flood_url(nodes: Sequence[Node], *, model: str = SEAMLESS, start: date | None = None, end: date | None = None, forecast_days: int | None = None, ensemble: bool = False) -> str` The URL of the daily discharge of `nodes`. With `start` and `end`: the history between them. With `forecast_days`: the forecast from today; `ensemble` adds the members. ### `parse_daily(payload: Any, nodes: Sequence[Node]) -> dict[Node, dict[date, float]]` `{node: {day: m³/s}}` from an answer; a day without a value is left out. ### `parse_members(payload: Any, nodes: Sequence[Node]) -> dict[Node, tuple[date, list[list[float]]]]` `{node: (first day, members)}` from an ensemble answer. `members` is (member, lead time) with NaN where there is no value, the control run first: what `glofas_ewds.ensemble.exceedance_probability` and `glofas_ewds.ensemble.peak_day` take. A node without a single value is left out. ### `fetch(url: str, *, timeout: float = 60.0, retries: int = 2, pause: float = 3.0) -> Any` The JSON at `url`; `glofas_ewds.errors.GlofasEwdsError` if it does not come. A request that fails (a timeout, a dropped connection) is sent again up to `retries` times, `pause` seconds apart. # Requests ## `glofas_ewds.request` The EWDS requests for GloFAS, built without sending them. Pure: nothing here does I/O. Each function returns the dict you pass to `cdsapi.Client.retrieve(dataset, request, target)`. Three choices matter more than they look: * **GloFAS 4, not 5.** Open-Meteo serves its forecast from GloFAS 4 (checked on 11 October 2026 at Faenza: 7.1 / 6.1 / 8.9 m³/s from the EWDS against 7.3 / 5.9 / 8.9 from Open-Meteo), and version 5 gives about half. A ratio of a v4 forecast to a v5 reference is a number without meaning. * **Consolidated, then intermediate.** The consolidated history arrives months late; the recent months exist only as `intermediate`, the same model and version. `historical_request` takes the product. * **The control run.** The forecast dataset holds an ensemble; the control run is the one Open-Meteo serves as `forecast_v4`. The 50 perturbed members (`ENSEMBLE`) say how likely a peak is, which one run cannot. ### `months(start: date, end: date) -> list[tuple[int, int, list[str]]]` `(year, month, days)` for every month between `start` and `end`, both included. The EWDS limits how much one request may hold; a month of Italy is well inside it, and a month is what you re-download when one fails. ### `historical_request(year: int, month: int, days: list[str], *, product: str = 'consolidated', area: Area = ITALY, version: str = GLOFAS_VERSION) -> dict[str, Any]` Daily mean discharge for `days` of one month; `product` is `consolidated` or `intermediate`. ### `forecast_request(run: date, *, days: int = FORECAST_DAYS, area: Area = ITALY, product: str = CONTROL) -> dict[str, Any]` The run of `run` (00 UTC), one step per 24 hours of lead time. `product` is `CONTROL` (one run, what Open-Meteo serves) or `ENSEMBLE` (the 50 perturbed members: about 50 times the size). ### `candidate_runs(today: date, *, latest_saved: date | None = None) -> list[date]` The forecast runs worth trying, newest first. GloFAS runs once a day at 00 UTC and the EWDS publishes it some hours later: early in the day today's run is usually missing, so yesterday's is the fallback. Runs you already have are left out. # Downloads ## `glofas_ewds.download` Download EWDS files to a folder, one month (or one run) per file. Synchronous, like `cdsapi`: from async code call these in a thread, or use `glofas_ewds.client.EwdsClient`. They work with any object that has `retrieve(dataset, request, target)`, so you can pass a `cdsapi.Client`, your own wrapper (a budget, a queue timeout) or a fake in tests. Every function can be run again: a file already there is not requested. Each download goes to `.part` and is renamed when complete, so a request you stopped waiting for never leaves half a file that passes for a whole one. ### `class Retriever()` What `cdsapi.Client` offers and these functions use. #### `Retriever.retrieve(name: str, request: dict[str, Any], target: str) -> Any` ### `download_history(folder: Path, start: date, end: date, *, client: Retriever, area: Area = ITALY) -> list[Path]` GloFAS 4 daily discharge, one NetCDF per month; intermediate where the consolidated history does not reach yet. ### `download_forecast(folder: Path, run: date, *, client: Retriever, area: Area = ITALY) -> Path` The control forecast of `run`, one NetCDF. ### `download_ensemble(folder: Path, run: date, *, client: Retriever, area: Area = ITALY) -> Path` The 50 perturbed members of `run`, one NetCDF (about 90 MB for Italy). ### `download_fire(folder: Path, start: date, end: date, *, client: Retriever, area: Area = ITALY) -> list[Path]` The Copernicus FWI components, one NetCDF per month. # Client ## `glofas_ewds.client` An async front for the EWDS downloads, for code that runs in an event loop. The EWDS is a queue: a request waits minutes before its file is ready, and `cdsapi` blocks while it waits. `EwdsClient` runs each download in a thread so your loop keeps serving. Credentials: pass `url` and `key`, or leave them out and `cdsapi` reads `CDSAPI_URL` / `CDSAPI_KEY` or `~/.cdsapirc`. Accept each dataset's licence once on its page on the EWDS, or every request answers 403. ### `cdsapi_client(url: str | None = None, key: str | None = None) -> Retriever` A quiet `cdsapi.Client` (needs the `ewds` extra). ### `class EwdsClient(folder: Path | str, *, url: str | None = None, key: str | None = None, retriever: Retriever | None = None, area: Area = ITALY)` GloFAS history and forecast, and the Copernicus FWI, downloaded off the event loop. #### `EwdsClient.retriever: Retriever` The object that sends the requests; a `cdsapi.Client` unless you gave one. #### `async EwdsClient.history(start: date, end: date) -> list[Path]` Daily discharge files from `start` to `end`; see `download_history`. #### `async EwdsClient.forecast(run: date) -> Path` The control forecast file of `run`; see `download_forecast`. #### `async EwdsClient.ensemble(run: date) -> Path` The perturbed members of `run`; see `download_ensemble`. #### `async EwdsClient.latest_forecast(*, today: date | None = None, latest_saved: date | None = None) -> tuple[date, Path] | None` The newest run you do not have yet: today's, or yesterday's if today's is not published. `None` when you already have the newest. Raises `GlofasEwdsError` when no candidate run could be downloaded. #### `async EwdsClient.fire(start: date, end: date) -> list[Path]` Copernicus FWI files from `start` to `end`; see `download_fire`. # GloFAS readers ## `glofas_ewds.glofas` GloFAS NetCDF files from the EWDS, read into numbers per node. Needs the `netcdf` extra (`netCDF4`). No network. Every reader takes your **nodes** (lon, lat points: river gauges, the centres of a grid, your assets) and reads, for each, the cell `glofas_ewds.cells.open_meteo_cell` chooses. What is not there stays absent: a node outside the file or on a masked cell (sea, no river network) gets no value, which is "no forecast here", never "the river is low". Forecast files are read by the **names** of their dimensions (member, lead time, run, latitude, longitude), not by their order, so the control run and the ensemble share one reader. A file whose dimensions are not recognised raises `glofas_ewds.errors.GlofasEwdsError` naming them. ### `discharge_series(files: Iterable[Path], nodes: Sequence[Node], *, start: date, end: date) -> dict[Node, list[float]]` Daily discharge (m³/s) of each node's cell between `start` and `end`. The EWDS `valid_time` is the **end** of the 24 hours averaged, so the day after the one you asked for: the series is keyed by the day asked. Masked values are dropped, not zeroed. ### `discharge_by_day(files: Iterable[Path], nodes: Sequence[Node], *, start: date, end: date) -> dict[Node, dict[date, float]]` Like `discharge_series`, with each value under its day. What `glofas_ewds.return_period.annual_maxima` needs. A day in two files (yesterday's partial month next to today's) is kept once. ### `forecast_peaks(path: Path, nodes: Sequence[Node]) -> dict[Node, float]` The highest forecast discharge (m³/s) in each node's cell, over all lead times (and members, in an ensemble file). Nodes outside the file or on a masked cell are left out. ### `ensemble_members(path: Path, nodes: Sequence[Node]) -> dict[Node, npt.NDArray[np.float64]]` Each node's forecast as a (member, lead time) array in m³/s, NaN where masked. For a control file there is one member. Feed it to `glofas_ewds.ensemble.exceedance_probability`. ### `forecast_peak_days(path: Path, nodes: Sequence[Node], run: date) -> dict[Node, date | None]` The day of `forecast_peaks`' peak for each node, for the file of `run`. See `glofas_ewds.ensemble.peak_day` for which day a lead time is. # Fire danger (FWI) ## `glofas_ewds.fwi` The official Copernicus Fire Weather Index from the EWDS. `cems-fire-historical-v1` is the Canadian FWI system computed by Copernicus on ERA5, from 1940 to a few days ago, at 0.25°. Put next to your own FWI it tells you whether your chain drifts (spin-up, rain, observation hour). The request builder is pure; `fire_values` needs the `netcdf` extra. Two traps. In the NetCDF the variables carry GRIB short names (`fwinx`, `drtcode`, ...), not the names you asked for, so they are recognised here by their `long_name`. And the build-up index is called "Fire buildup index" in the file, not "Build up index" as in the request. ### `fire_request(year: int, month: int, days: list[str], *, product: str = 'consolidated_dataset', area: Area = ITALY) -> dict[str, Any]` The six FWI components for `days` of one month; `product` is `consolidated_dataset` or `intermediate_dataset`. ### `fire_values(paths: Iterable[Path], nodes: Sequence[Node]) -> dict[tuple[Node, date], dict[str, float]]` For each (node, day), the FWI components of the node's cell. A cell without data (sea, outside the file) gives no row: absent, not zero. # Reference and ratio ## `glofas_ewds.reference` A node's ordinary high flow, and how far a forecast is above it. Pure: nothing here does I/O. A forecast of 300 m³/s means nothing on its own: it is a flood on a torrent and a dry summer on the Po. Dividing by the node's **own** reference, a high percentile of its multi-year series, makes rivers comparable. Dividing by a regional figure does not: 10 % of the Po is 186 m³/s, more than most rivers ever carry. ### `percentile(values: Sequence[float], p: float) -> float | None` The `p` quantile (0-1) by linear interpolation; `None` for no values. ### `references(series: Mapping[K, Sequence[float]], *, p: float = 0.9, min_days: int = MIN_REFERENCE_DAYS) -> dict[K, float | None]` The `p` quantile of each series; `None` below `min_days` values. ### `discharge_ratio(peak: float | None, reference: float | None) -> float | None` `peak / reference`; `None` when either is unknown or the reference is 0. `None` means "I don't know how big this river is", never "the river is low". ### `reference_before(by_day: Mapping[date, float], start: date, *, p: float = 0.9, min_days: int = MIN_REFERENCE_DAYS) -> float | None` A node's reference from the days **before** `start` only. For a replay: a reference that contains the days being judged already knows about the event. `None` below `min_days` earlier days. ### `peak_ratios(by_day: Mapping[date, float], reference: float | None, *, window_days: int = PEAK_WINDOW_DAYS) -> dict[date, float]` For each day, the peak of the `window_days` from it over `reference`. What a forecast issued that day would have given, replayed on a daily series: `discharge_ratio` with the window slid by hand. Days missing from the window are skipped; an unknown or non-positive reference gives no ratios, never zeros. # Ensemble ## `glofas_ewds.ensemble` How likely a forecast peak is: the share of ensemble members above a threshold. Pure: nothing here does I/O. The control run says one future; the 50 perturbed members of the same run say how sure it is. Three members over the river's ordinary high flow and forty over it are the same control forecast and very different news. The threshold is yours: a node's own reference (`glofas_ewds.reference.references`) or a return level (`glofas_ewds.return_period.return_levels`), never a regional figure. A member that is all NaN (masked) does not vote. With no member left, or no threshold, the answer is `None`: "I don't know", never "0 %". ### `exceedance_probability(members: npt.ArrayLike, threshold: float | None) -> float | None` Share (0-1) of members whose peak over the lead times reaches `threshold`. `members` is (member, lead time), as `glofas_ewds.glofas.ensemble_members` gives it. ### `exceedance_by_lead(members: npt.ArrayLike, threshold: float | None) -> list[float] | None` For each lead time, the share of members at or above `threshold`. Says *when*: `[0.0, 0.1, 0.6, 0.4, ...]` is a peak most likely on day 3. A lead time where every member is masked gives NaN. ### `peak_day(members: npt.ArrayLike, run: date) -> date | None` The day of the highest value of a (member, lead time) forecast of `run`. The k-th lead time (`leadtime_hour` 24·(k+1)) is the mean of the day `run + k`: the GloFAS `valid_time` is the end of the day. A single series (lead time only) is one member. `None` when everything is masked. # Return periods ## `glofas_ewds.return_period` Return levels of a river from its own GloFAS history: the 2-, 5-, 20-year flow. Pure: nothing here does I/O. The EWDS does not serve GloFAS's flood thresholds, and the 90th percentile of two years (`glofas_ewds.reference.references`) is "an ordinary high flow", not "a flood that comes once in five years". This module fits a Gumbel distribution to the **annual maxima** of a node's reanalysis, by L-moments, and reads the levels off it. Two cautions. These are **not** the official GloFAS thresholds: same family of method, but your years, your cells, your fit. And a fit needs decades: the reanalysis starts in 1979, and fewer than `min_years` complete years give `None`. ### `annual_maxima(by_day: Mapping[date, float], *, min_days: int = MIN_DAYS_PER_YEAR) -> dict[int, float]` The highest value of each calendar year with at least `min_days` values. `by_day` is one node of `glofas_ewds.glofas.discharge_by_day`. ### `gumbel_fit(maxima: npt.ArrayLike) -> tuple[float, float]` Location and scale of a Gumbel, by L-moments (Hosking 1990). Needs at least two values. ### `return_level(location: float, scale: float, years: float) -> float` The flow exceeded on average once every `years` years. ### `return_levels(maxima: Iterable[float], *, periods: Sequence[float] = RETURN_PERIODS, min_years: int = MIN_YEARS) -> dict[float, float] | None` `{period: level}` from a node's annual maxima; `None` below `min_years` or when the maxima do not vary (a dry cell). ### `class FloodLabel(years: int | None, peak: float, thresholds: dict[int, float], day: date | None = None)` A forecast peak said in return periods: "above the 5-year flood". ### `flood_label(ratio: float | None, reference: float | None, thresholds: Mapping[int, float | None], forecast: tuple[float, date | None] | None = None, *, tolerance: float = PEAK_TOLERANCE) -> FloodLabel | None` The forecast peak as a return-period label; `None` when a piece is missing. The peak is recovered exactly as `ratio * reference` (`glofas_ewds.reference.discharge_ratio` undone) and compared with `thresholds`, `{years: m³/s}` for the same cell: the official ones (`glofas_ewds.thresholds.flood_thresholds`) or your own (`return_levels`). Unknown or non-positive thresholds are ignored. Without a reference or without the 2-year threshold there is no label: "I don't know" is not "below the flood". `forecast` is `(peak, day)` of a saved run. Its day is kept only when its peak is within `tolerance` of the recovered one: further apart, the ratio came from another run and the day belongs to another forecast. # Official thresholds ## `glofas_ewds.thresholds` The official GloFAS v4 flood thresholds: the 2-, 5- and 20-year flow of a cell. `threshold_url` and `threshold_file_name` are pure; the readers need the `netcdf` extra. No network: download the files with your own client. The EWDS does not serve the thresholds. ECMWF publishes them as "GloFAS auxiliary data": three global NetCDF files at 0.05° (about 165 MB each), public and without credentials, one per return period. For each node the readers take the cell the node already reads for the forecast and the reference, the one `glofas_ewds.cells.open_meteo_cell` chooses: a wrong cell on a river is a factor of ten. Compare with `glofas_ewds.return_period.return_levels`, which fits your own levels from a node's reanalysis: these are the official ones. ### `threshold_file_name(years: int) -> str` The name ECMWF gives the file of the `years`-year flood. ### `threshold_url(years: int) -> str` The public URL of the file of the `years`-year flood. ### `read_threshold(path: Path, nodes: Sequence[Node]) -> list[float | None]` The threshold (m³/s) of one file in each node's cell, in the order of `nodes`. `None` for a node outside the file or on a cell that is masked or not positive (sea, no river network). Only the rectangle that contains the nodes is read: the file is the world. ### `threshold_window(path: Path, longitude: float, latitude: float, *, radius_km: float = 15.0) -> dict[Node, float]` The cells with a threshold around a point, `{cell centre: m³/s}`. Every cell of the file whose centre is within `radius_km` and holds a positive value. What `glofas_ewds.rivers.nearest_river` looks for a river in: along a channel the 2-year flow is one or two orders of magnitude above the cells beside it. ### `flood_thresholds(files: Mapping[int, Path], nodes: Sequence[Node]) -> dict[Node, dict[int, float | None]]` `{node: {years: m³/s}}` from `{years: file}`. Each node's value is what `glofas_ewds.return_period.flood_label` takes as `thresholds`. # Errors ## `glofas_ewds.errors` The exceptions this package raises. ### `class GlofasEwdsError()` An EWDS request failed, or a file is not one this package can read. # For Limen: what to take from here [Limen](https://github.com/agent-engineering-studio/limen) is the application this library was extracted from. This page lists what Limen still computes on GloFAS data on its own, and what it lacks that the library now has. It is a list for whoever adopts a release, not a promise of what Limen does. ## What Limen can delete (since 0.3.0) | In Limen | Use instead | |---|---| | `core/piena.py`: `piena`, `Piena`, `TOLLERANZA_PICCO` | `flood_label`, `FloodLabel`, `PEAK_TOLERANCE` | | `integrations/openmeteo/flood.py`: `percentile_of`, `MIN_REFERENCE_DAYS` | `percentile`, `MIN_REFERENCE_DAYS` | | `cli/backtest_flood.py`: `_discharge_ratios`, `_node_reference` | `peak_ratios`, `reference_before` | | `integrations/copernicus/ewds_glofas.py`: `giorno_del_picco`, `giorni_dei_picchi` | `peak_day`, `forecast_peak_days` | | `integrations/copernicus/glofas_soglie.py`: `leggi`, `soglie`, `nome_file`, `URL` | `read_threshold`, `flood_thresholds`, `threshold_file_name`, `threshold_url` | `flood_thresholds` returns `{node: {years: value}}`, not Limen's 3-tuple: the callers of `soglie` have to be adapted. ## What Limen still computes on GloFAS data - **The Open-Meteo flood client** (`integrations/openmeteo/flood.py`, 785 lines): the URLs, the batches, the parsing of the daily series. Since 0.4.0 the library has a small keyless reader (`glofas_ewds.openmeteo`: `flood_url`, `parse_daily`, `parse_members`). It does not replace Limen's client, which has its own retry, cache and quota; the URL builder and the two parsers can be shared. - **The quota arithmetic** of the nightly fill (`glofas_riferimenti.py`: calls per node, pause between batches). It is about Open-Meteo's limits, not about GloFAS: it stays in Limen. - **The fluvial signal**: the forecast peak over the node's 90th percentile, and its thresholds in `flood.yaml`. The ratio is the library's (`discharge_ratio`); the decision is Limen's. ## What Limen lacks, and is here since 0.4.0 - **The ensemble in the decision.** Limen reads the control run. The 50 members are downloaded by `download_ensemble` and counted by `credibility`: how many reach the 2-year flow. A fluvial alert on one control run with three members behind it is the weakest alarm there is. - **Persistence between runs.** `credibility(..., previous=...)` counts how many runs in a row forecast the level for the same days. Limen stores one peak per run (`glofas_previsione`): the members of the last runs would have to be kept, or at least the control series. - **Trust per node.** `trust(river)` gives a level by the size of the river, with the record of known floods: 25 of 28 from long rain, 4 of 13 flash floods. Limen's open problem on floods is false alarms, and the other half of it is missed alarms: on a small basin the fluvial branch cannot see a flash flood, and should not be the one that speaks. That is a job for rain (the radar, the rain thresholds), not for discharge. - **The river cell of a node.** Limen's river nodes are a lattice; a node's own cell is often beside the river. `nearest_river` on the official 2-year flow finds the channel, and `River.own_size` says what the node was reading. - **A flood label without a ratio.** `Facts.discharge` labels a value against the thresholds of its cell even with a short history. ## What neither has - **A calibration of the forecast.** How often a peak with a given share of members and a given persistence is followed by a flood. It needs the archive of past forecasts (`cems-glofas-reforecast`), an EWDS key and hours of queue. It is the next step for this library. - **Dams.** The model's thresholds do not know a river is regulated. # Per un ente pubblico Questa pagina è per chi lavora in un Comune, in una Provincia o in una protezione civile e vuole mettere sul proprio sito il fiume del territorio. ## Che cosa ottieni Una pagina web, in italiano e in inglese, costruita con Bootstrap Italia, che per un luogo mostra: - **il fiume più vicino** e quanto ci si può fidare del modello su quel fiume; - **la portata dell'ultimo giorno** rispetto alla storia di quello stesso fiume; - **il picco previsto** per la settimana, il periodo di ritorno che raggiunge, quanti dei 51 scenari della previsione lo confermano; - **quanto sono vecchi i dati**, in alto, prima dei numeri. I numeri vengono da GloFAS, il modello dei fiumi del servizio Copernicus per la gestione delle emergenze. La pagina non li calcola: li legge. ## Che cosa non è **Non è un sistema di allerta e non lo deve diventare.** Non mostra aree allagate, non mostra la pioggia, non dà un livello di rischio. L'allerta ufficiale è il bollettino della protezione civile: la pagina lo dice in ogni schermata. E c'è un limite da conoscere prima di pubblicarla: **GloFAS non vede le alluvioni lampo.** Su 41 alluvioni italiane note dal 1997, il modello ha raggiunto la propria soglia dei 2 anni in 25 delle 28 dovute a piogge di più giorni e in 4 delle 13 dovute a temporali di poche ore. A Senigallia, il 15 settembre 2022, il modello dà 0,4 m³/s su una cella la cui piena da 2 anni è 33,4 m³/s. Su un torrente la pagina lo scrive: fiducia «scarsa», con il conto delle alluvioni note. ## Come si installa Serve solo Docker. ```bash git clone https://github.com/agent-engineering-studio/glofas-ewds cd glofas-ewds docker compose up ``` La pagina è su , con sei luoghi di esempio. Per il tuo: ```bash docker compose run --rm cli init --place "Nome del Comune,longitudine,latitudine" ``` Il comando scarica una volta le soglie ufficiali (circa 520 MB), trova la cella del fiume e scarica cinque anni di storia e la previsione. Poi nel file `.env`: ```bash GLOFAS_EWDS_PLACE=nome-del-comune ``` Per tenere i dati aggiornati, una volta al giorno: ```bash docker compose run --rm update ``` ## Che cosa resta a chi pubblica - **L'HTTPS e il proxy** davanti alla pagina: vedi `SECURITY.md`. - **L'aggiornamento quotidiano**: se non gira, la pagina lo dice («i dati hanno N giorni»), ma resta vecchia. - **La fonte dei dati.** Senza account la pagina legge Open-Meteo, un servizio terzo che distribuisce gli stessi numeri di GloFAS 4 con la sua licenza (CC BY 4.0, uso non commerciale, 10.000 chiamate al giorno). Per un sito istituzionale conviene la fonte ufficiale, l'Early Warning Data Store di Copernicus: account gratuito, `--source ewds`. - **La citazione.** Chi pubblica dati derivati da GloFAS deve scrivere «Contiene informazioni modificate del Copernicus Emergency Management Service [anno]». ## Dati personali e intelligenza artificiale La pagina non raccoglie dati personali, non ha login e non usa cookie. Non chiama nessun modello di intelligenza artificiale. La libreria offre a chi costruisce un assistente i fatti (`Facts`), con le regole per citarli (`ANSWER_RULES`), solo con numeri calcolati dai dati, e un controllo (`check_text`) che rifiuta un testo con numeri che nei dati non ci sono. ## Catalogo del riuso Il file `publiccode.yml` descrive il software per il catalogo di Developers Italia. Licenza Apache-2.0. # Contributing Issues and pull requests are welcome. - Run `make check` before pushing: ruff, `mypy --strict` and pytest must be clean, the same gate CI runs. - A change to a cell, a request or a reader should also pass the live contract tests (`tests/test_live.py`, needs an EWDS key): see the README's Development section. CI runs them weekly. - Commits follow [Conventional Commits](https://www.conventionalcommits.org/). - Contributions are accepted under the project's license, Apache-2.0 (section 5 of the license: inbound = outbound). No separate CLA. --- name: glofas-ewds description: Read river discharge from GloFAS, the global flood model of Copernicus, in Python with the glofas-ewds library - the river cell of a place, daily discharge against the river's own history, the forecast peak and its return period against the official 2-, 5- and 20-year thresholds, ensemble members, how far the model can be trusted on a river, facts for an assistant, the Copernicus fire danger indices. Use when code or an answer needs river discharge, flood forecasts or return periods for a place, or mentions GloFAS, EWDS, Early Warning Data Store, CEMS, Open-Meteo flood API, cems-glofas or glofas-ewds. --- # glofas-ewds `glofas-ewds` is a typed Python library for GloFAS 4 river discharge and the Copernicus fire danger indices, from the Early Warning Data Store (EWDS) or, with no account, from the Open-Meteo flood API. Use it rather than raw requests and your own rounding: picking the wrong 0.05° cell changes a river by a factor of ten and nothing raises an error. Full documentation: https://agentengineering.it/glofas-ewds/ · everything as plain text: https://agentengineering.it/glofas-ewds/llms-full.txt ## Setup ```bash pip install glofas-ewds # pure functions; needs only numpy pip install "glofas-ewds[netcdf]" # + read EWDS files and the official thresholds pip install "glofas-ewds[ewds,netcdf]" # + download from the EWDS (cdsapi, an account) ``` Python 3.12 or newer. Open-Meteo and the ECMWF threshold files need no key. The EWDS needs a free account, its key in `CDSAPI_URL` / `CDSAPI_KEY` or `~/.cdsapirc`, and the licence of each dataset accepted once on its page (until then every request answers 403). ## The data, in one paragraph - GloFAS 4 gives the **mean discharge of a day**, in m³/s, on a **0.05° grid** (about 5 km), from a model: a reanalysis of the past and a daily forecast (one control run and 50 perturbed members). - A **node** is a `(lon, lat)` point; it reads the cell `open_meteo_cell(lon, lat)`. - The **official thresholds** (2-, 5-, 20-year flow of each cell) are three public NetCDF files of ECMWF, about 173 MB each: not on the EWDS. - A **store** is a folder of places (`glofas-ewds init`), each with its river cell, thresholds, history and last forecast runs. `Facts` and the demo read the store and never the network. ## What to tell people before any number - **GloFAS does not hold flash floods.** On 41 known Italian floods its reanalysis reached its own 2-year flow in 25 of 28 floods from days of wide rain and in 4 of 13 flash floods. Senigallia, 15 September 2022: 0.4 m³/s on a cell whose 2-year flood is 33.4. On a small river say so first. - A discharge is a model's daily mean on a cell: **not a gauge reading**. - **Nothing here is an alert.** The alert is the civil-protection bulletin. ## Recipes ```python from glofas_ewds import Facts, Store, check_text, credibility, local, trust folder = local.data_folder() # $DATA_ROOT/glofas-ewds, else ~/.cache/glofas-ewds files = local.download_thresholds(folder) # about 520 MB, once place = local.locate("Faenza", 11.88, 44.29, files) # its river cell and thresholds local.fill_from_open_meteo([place], years=5) # history and the newest forecast, no key Store(folder).save(place) place.river # River(cell, size (2-year flow), distance_km, own_cell, own_size) trust(place.river) # Trust(level, size, reasons, seen, known) facts = Facts(Store(folder)) facts.discharge("faenza") # last day, share of days below, ratio to its own q90, return period facts.forecast("faenza") # peak, day, return period, ensemble, persistence, source, age_days check_text("The peak is 180 m³/s.", facts.summary("faenza")) # ['180']: not in the facts facts.check_text("faenza", "The peak is 180 m³/s.") # the same, with "faithful": False ``` **Building an assistant on it.** The package serves no protocol. Expose each method of `Facts` (`places`, `river`, `discharge`, `forecast`, `summary`, `check_text`) as one tool, and give the model `ANSWER_RULES` (from `glofas_ewds`) as its instructions: the rules for wording an answer from these facts. The same from the shell: ```bash glofas-ewds init --place "Faenza,11.88,44.29" # once glofas-ewds update # daily: the newest forecast glofas-ewds facts faenza --about forecast glofas-ewds find 11.88 44.29 # the river cell of a point, storing nothing ``` From EWDS files instead (the source of record): ```python from datetime import date from glofas_ewds import EwdsClient, discharge_series, ensemble_members, references ewds = EwdsClient("data/ewds") history = await ewds.history(date(2024, 11, 1), date(2026, 10, 31)) # monthly files series = discharge_series(history, nodes, start=date(2024, 11, 1), end=date(2026, 10, 31)) ref = references(series, p=0.9) # None below a year of days run, control = await ewds.latest_forecast() # today's run, or yesterday's members = ensemble_members(await ewds.ensemble(run), nodes) # {node: (member, lead time)} ``` ## Rules 1. **Never round a point to a cell yourself.** `open_meteo_cell(lon, lat)` is the cell both the EWDS readers and Open-Meteo give for a point (Open-Meteo's values belong to the cell one step east of the one it declares). `point_for_cell(cell)` is the way back. 2. **The river of a town is not the cell under the town.** Find it with `local.locate` or `nearest_river`; read `River.distance_km` and `own_size`. It picks the largest river within 10 km: pass `radius_km` when a bigger river flows nearby. 3. **Never read a discharge alone.** Compare it with the river's own history (`references`, `discharge_ratio`) or its own thresholds (`flood_label`). Never interpolate between cells. 4. **`None` is "not known"**, never "low" and never "no flood". In the facts, a `return_period_years` of `None` is "below the 2-year flow" only when `below_two_year_flow` is true. 5. **Say the source and the age.** Every fact has `source`, `fetched` and `age_days`. A forecast is a forecast: quote its run. 6. **`credibility` is facts, not a verdict.** Members over the 2-year flow and runs in a row; `runs_in_a_row` is `None` when no earlier run is stored. Do not turn the share into a probability of flooding. 7. **Quote `trust` with its record**, and say the record is of the reanalysis, not of the forecasts of the time. 8. **GloFAS 4, not 5** (`version_4_0` is pinned): version 5 gives about half. 9. **Two sources, not interchangeable for the past.** Open-Meteo's reanalysis starts on 1 January 1997, and after 2024 its history is its archive of forecasts; the EWDS reanalysis starts in 1979. Open-Meteo counts a call per two weeks per point, 10,000 a day. 10. **Run `check_text` on any text with numbers** written from the facts. It refuses a number that is not a fact; it cannot see a real number said of the wrong thing, so read the sentence too. 11. The fire danger indices (`fire_request`, `download_fire`, `fire_values`) are here, not in a wildfire library: this package is organised by source.