Metadata-Version: 2.4
Name: glofas-ewds
Version: 0.4.0
Summary: GloFAS river discharge and Copernicus fire danger from the EWDS, on the right grid cell: the river of a place, its history, the forecast and how far to trust it
Keywords: glofas,copernicus,ewds,river discharge,flood,fire weather index,cems
Author: Giuseppe Zileni
Author-email: Giuseppe Zileni <giuseppe.zileni@gmail.com>
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Hydrology
Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
Classifier: Typing :: Typed
Requires-Dist: numpy>=2.0
Requires-Dist: cdsapi>=0.7 ; extra == 'ewds'
Requires-Dist: mcp>=2.3 ; extra == 'mcp'
Requires-Dist: netcdf4>=1.7 ; extra == 'netcdf'
Requires-Python: >=3.12
Project-URL: Homepage, https://github.com/agent-engineering-studio/glofas-ewds
Project-URL: Issues, https://github.com/agent-engineering-studio/glofas-ewds/issues
Project-URL: Documentation, https://agentengineering.it/glofas-ewds/
Project-URL: Changelog, https://github.com/agent-engineering-studio/glofas-ewds/blob/main/CHANGELOG.md
Provides-Extra: ewds
Provides-Extra: mcp
Provides-Extra: netcdf
Description-Content-Type: text/markdown

# 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
```

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/agent-engineering-studio/glofas-ewds/main/docs/images/cells-dark.png">
  <img alt="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." src="https://raw.githubusercontent.com/agent-engineering-studio/glofas-ewds/main/docs/images/cells-light.png">
</picture>
<sub>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
<a href="https://github.com/agent-engineering-studio/glofas-ewds/blob/main/docs/make_images.py"><code>docs/make_images.py</code></a>.</sub>

- [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`, an MCP server 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`, `netCDF4` and `mcp` 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 mcp` | the MCP server (`--http` for a port) |
| `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` | <http://localhost:3008> |
| The MCP server | `docker compose --profile mcp up mcp` | <http://localhost:8773/mcp> |
| Jupyter with the notebooks | `docker compose --profile notebooks up notebooks` | <http://localhost:8886> |
| 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-mcp`, `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

<img alt="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." src="https://raw.githubusercontent.com/agent-engineering-studio/glofas-ewds/main/docs/images/demo-comune.png" width="420">

`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<br/>(lon, lat)"] --> C["open_meteo_cell<br/>the cell to read"]
    R["historical_request<br/>forecast_request<br/>fire_request"] --> Q["EWDS queue<br/>(cdsapi)"]
    Q -->|"NetCDF, one per month / run"| D["download_*<br/>.part, then rename"]
    D --> S["discharge_series<br/>forecast_peaks<br/>fire_values"]
    C --> S
    S --> P["references (p90)<br/>discharge_ratio"]
```

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/agent-engineering-studio/glofas-ewds/main/docs/images/series-dark.png">
  <img alt="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." src="https://raw.githubusercontent.com/agent-engineering-studio/glofas-ewds/main/docs/images/series-light.png">
</picture>
<sub>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.</sub>

## 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".
- **The MCP server** serves them as tools (`places`, `river`, `discharge`,
  `forecast`, `summary`, `check_text`), from the store, with no network:

  ```bash
  pip install "glofas-ewds[mcp]"
  claude mcp add glofas-ewds -- glofas-ewds mcp
  ```

- **`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).
