# fwi-chain > A small Python library with no dependencies for the Canadian Fire Weather Index chain (Van Wagner 1987): FFMC, DMC, DC, ISI, BUI and FWI from four noon readings, one day at a time with an explicit state; walking a chain over many days from a stored point, redoing it when better rain arrives, a climatology in 21 quantiles, the EFFIS danger classes, and what moved the index from one day to the next. It also gives the answers as facts, an MCP server and a check that a text quotes the numbers right. Source: https://agentengineering.it/fwi-chain/ # fwi-chain **The Canadian Forest Fire Weather Index (FWI) System as small, pure, typed Python functions.** It has no dependencies and is measured in CI against the 48-day test series of `cffdrs`. Give it the weather at noon and it tells you how easily a wildfire would start, how fast it would spread, and how hard it would be to fight. That is the same index that national fire services and the European Forest Fire Information System (EFFIS) publish every day. ```bash pip install fwi-chain ``` --- ## Contents - [What is the Fire Weather Index?](#what-is-the-fire-weather-index) - [Quick start](#quick-start) - [See it in action](#see-it-in-action) - [Why fwi-chain](#why-fwi-chain) - [Examples](#examples) - [Documentation](#documentation) - [Contributing](#contributing) - [Reference and citation](#reference-and-citation) --- ## What is the Fire Weather Index? The FWI System was developed by the Canadian Forest Service (Van Wagner, 1987) and is now the most widely used fire danger rating system in the world. It takes **four weather readings at local noon**: | Input | Unit | |---|---| | Air temperature | °C | | Relative humidity | % | | Wind speed at 10 m | km/h | | Rain over the previous 24 hours | mm | From these it computes **six numbers**: | Code | Name | What it tracks | Memory | |------|------|----------------|--------| | **FFMC** | Fine Fuel Moisture Code | dryness of litter, needles and grass: *will a spark catch?* | ~16 hours | | **DMC** | Duff Moisture Code | dryness of the loose organic layer below | ~12 days | | **DC** | Drought Code | deep, seasonal drought in compact organic soil | ~52 days | | **ISI** | Initial Spread Index | FFMC × wind: *how fast would it run?* | — | | **BUI** | Buildup Index | DMC + DC: *how much fuel is there to burn?* | — | | **FWI** | Fire Weather Index | ISI + BUI: *how intense would the fire be?* | — | The key idea is that **the three moisture codes have memory**. Today's value depends on yesterday's, so the FWI is a *chain* that runs day after day through the fire season. `fwi-chain` makes that memory an explicit value (`FwiState`) that you store wherever you like. > New to fire weather? Read **[How the FWI works, in plain words](https://agentengineering.it/fwi-chain/how-fwi-works/)**. ## Quick start ```python from fwi_chain import STANDARD_PARAMS, advance state = STANDARD_PARAMS.initial_state # FFMC/DMC/DC = 85 / 6 / 15, the spring start-up out = advance( state, month=4, temperature_c=17.0, relative_humidity_pct=42.0, wind_speed_kmh=25.0, rain_24h_mm=0.0, params=STANDARD_PARAMS, ) print(round(out.fwi, 2)) # 10.1 state = out.state # store it: tomorrow starts from here ``` A whole season is just a loop: ```python state = STANDARD_PARAMS.initial_state for day in noon_observations: # your weather, one row per day, in order out = advance( state, month=day.month, temperature_c=day.temp, relative_humidity_pct=day.rh, wind_speed_kmh=day.wind, rain_24h_mm=day.rain, params=STANDARD_PARAMS, ) state = out.state # the chain: today's output, tomorrow's input print(day.date, round(out.fwi, 1)) ``` Each of the six equations is also exported on its own (`fine_fuel_moisture_code`, `duff_moisture_code`, `drought_code`, `initial_spread_index`, `buildup_index`, `fire_weather_index`), so you can ask what-if questions directly. See the [API reference](https://agentengineering.it/fwi-chain/api/). ## See it in action Every chart below is computed by `fwi-chain` itself from a synthetic, reproducible Mediterranean season. Regenerate them with `make figures`. **A fire season, day by day.** Spring rain keeps the index low. Through the summer, drought builds up, and one windy September day pushes the FWI past 100. ![FWI through a synthetic fire season with the rain below it](https://raw.githubusercontent.com/agent-engineering-studio/fwi-chain/main/docs/images/fire-season.svg) **Three memories.** The same weather drives all three moisture codes, but they forget at very different speeds. FFMC jumps back within a day of rain. The Drought Code climbs slowly all summer and keeps its memory for weeks. ![The three moisture codes over the season](https://raw.githubusercontent.com/agent-engineering-studio/fwi-chain/main/docs/images/moisture-codes.svg) **Why the state matters.** Restart the chain on 1 July from the spring default codes and it underestimates the danger for weeks, because it has "forgotten" a dry spring. That is why `fwi-chain` hands you the state instead of hiding it. ![A cold restart on 1 July compared with a chain that carried its state from April](https://raw.githubusercontent.com/agent-engineering-studio/fwi-chain/main/docs/images/restart.svg) ## Why fwi-chain - **Zero dependencies, scalar, pure.** No NumPy, no xarray, no I/O, no clock. It fits in a database job, a stream processor, or a serverless function. For gridded climate data, [xclim](https://github.com/Ouranosinc/xclim)'s vectorised FWI is the better tool. - **The state is explicit.** One call is one day. You choose how to persist and resume the chain (a table, a file, a cache), instead of having it hidden in an array dimension. - **Measured, not just tested.** A benchmark in CI walks the 48-day test series of `cffdrs` and compares the six codes with cffdrs's own output: at most 0.25 FWI points apart, the same EFFIS class on all 48 days. The difference has a known cause (two constants printed differently in 1985 and 1987); `CFFDRS_PARAMS` takes the 1985 ones and matches cffdrs to 0.006. The suite also covers every rain branch, physical bounds under extreme weather, and the memory of the codes. See [Validation](https://agentengineering.it/fwi-chain/validation/). - **Readable.** About 300 lines, with every line tied to an equation number in Van Wagner's report. It works as a reference implementation as well as a library. - **Typed.** Ships `py.typed` and passes `mypy --strict`. Frozen dataclasses, keyword-only arguments, and units in every parameter name (`wind_speed_kmh`, `rain_24h_mm`). `fwi-chain` was extracted from [Limen](https://github.com/agent-engineering-studio/limen), where it runs the wildfire danger chain for every ~9 km weather node in Italy. ## Many days, facts and an MCP server Since 1.1 the library also walks a chain over many days from a state you stored (`catch_up`, `walk_chain`), redoes it when better rain arrives (`correct_rain`) and places a value in the climatology of its place and month (`quantiles`, `percentile`). Since 1.3 it also reads the noon observation out of hourly weather (`noon_readings`), refusing a reading taken far from noon or with hours of rain missing. Since 1.2 it says **what moved the index**. On 7 May 1985, in the test series of `cffdrs`, the FWI went from 21.7 to 52.6: ```text the chain's memory +1.2 wind +18.0 12 -> 27 km/h humidity +11.1 33 -> 17 % temperature +0.6 27 -> 28 °C rain +0.0 ``` The same answers come as plain data (`fwi_chain.facts`), with a check that a text quotes them right (`fwi_chain.check.check_text`) and an MCP server for AI agents (`pip install "fwi-chain[mcp]"`, then `fwi-chain-mcp`). The rule of all three: the numbers come from the chain; a model may explain them, never invent them. See [Facts, explanation and MCP](https://agentengineering.it/fwi-chain/ai/). > **A fire weather index is not an alert**, and not a forecast of fires. The official > fire danger for Europe is published by [EFFIS](https://forest-fire.emergency.copernicus.eu/). The danger classes (`effis_class`: low, moderate from 11.2, high from 21.3, very high from 38, extreme from 50, very extreme above 70) are the ones EFFIS publishes in its [technical background](https://forest-fire.emergency.copernicus.eu/about-effis/technical-background/fire-danger-forecast), read on 2026-11-28. If EFFIS changes them, the library follows in a new release. ## Try it with Docker ```bash docker compose up # a page for a public body on :3007, notebooks on :8885 docker compose --profile mcp up mcp # the MCP server on :8772/mcp make help # every target ``` The page (`app/`, in Italian) shows the chain of one place day by day from the weather you give it, and what moved the index. It fetches no weather, no fires, no forecast. ## Examples Runnable, dependency-free scripts live in [`examples/`](examples/). CI runs every one of them, so they always match the code. | Script | What it shows | |---|---| | [`01_single_day.py`](examples/01_single_day.py) | One day of the chain, all six outputs explained | | [`02_fire_season.py`](examples/02_fire_season.py) | A full season, danger classes, CSV export | | [`03_daily_job_sqlite.py`](examples/03_daily_job_sqlite.py) | A daily job that persists the state in SQLite and resumes | | [`04_many_stations.py`](examples/04_many_stations.py) | One state per station or grid cell, as in production | | [`05_southern_hemisphere.py`](examples/05_southern_hemisphere.py) | Custom `FwiParams` for other latitudes | | [`06_individual_equations.py`](examples/06_individual_equations.py) | What-if analysis with the individual equations | ```console $ python examples/02_fire_season.py 214 days, 2026-04-01 to 2026-10-31 Peak FWI 103.76 on 2026-09-13 (wind 47.4 km/h) Days per danger class: low 60 ############################## moderate 33 ################ high 64 ################################ very high 34 ################# extreme 19 ######### very extreme 4 ## ``` ## Documentation | Guide | For whom | |---|---| | [How the FWI works](https://agentengineering.it/fwi-chain/how-fwi-works/) | Everyone: the science in plain words, with pictures | | [Getting started](https://agentengineering.it/fwi-chain/getting-started/) | Developers: from `pip install` to a daily job, plus common mistakes | | [Cookbook](https://agentengineering.it/fwi-chain/cookbook/) | Recipes: pandas, CSV, SQLite, many stations, parallelism, units, HTTP service | | [API reference](https://agentengineering.it/fwi-chain/api/) | Every public function and class | | [Facts, explanation and MCP](https://agentengineering.it/fwi-chain/ai/) | What moved the index, the answers as data, the text check, the MCP server | | [Validation](https://agentengineering.it/fwi-chain/validation/) and [Benchmark](https://agentengineering.it/fwi-chain/benchmark/) | What the numbers are measured against, and what they are not | | [Riuso](https://agentengineering.it/fwi-chain/riuso/) | In Italian, for a public body | | [FAQ](https://agentengineering.it/fwi-chain/faq/) | Short answers to common questions | ## Contributing **Contributions are very welcome**, whether you are a fire scientist, a meteorologist, a Python developer, or someone who writes clear docs. Some ideas: - 🔬 Add reference cases to the benchmark: another implementation, a fire service's published values - 🌍 Contribute day-length tables for other latitude bands - 📈 Implement the Daily Severity Rating, hourly FFMC, or DC overwintering - 📝 Improve the docs, translate them, or write a tutorial for your region - 🐛 Report anything that disagrees with a reference implementation Start with **[CONTRIBUTING.md](CONTRIBUTING.md)**. It covers a five-minute dev setup, the project layout, and a list of good first issues. ## Reference and citation Van Wagner, C.E. (1987). *Development and structure of the Canadian Forest Fire Weather Index System*. Canadian Forestry Service, Forestry Technical Report 35. The equation numbers in the source comments are that report's. If `fwi-chain` helps your work, a link back or a ⭐ on GitHub helps other people find it. ## License [Apache-2.0](./LICENSE). # How the Fire Weather Index works, in plain words This page explains the Canadian Forest Fire Weather Index (FWI) System without assuming any background in fire science. It covers what each number means, why the system is a *chain*, and how `fwi-chain` turns it into code. ![The FWI chain](images/fwi-chain-diagram.svg) ## The question the FWI answers On any given day, a forest manager wants to know: 1. *If a fire started today, would it catch?* 2. *How fast would it spread?* 3. *How much fuel would it consume, and how hard would it be to put out?* The answers depend on how **dry** the fuels on the forest floor are. Dryness depends on the weather of today, but also of the past days, weeks and months. A forest after a dry summer burns very differently from the same forest after a wet one, even under identical weather today. The FWI System, published by C.E. Van Wagner for the Canadian Forest Service in 1987, answers these questions with **six numbers** computed from **four weather readings** taken every day at local noon. ## The inputs: four noon readings | Input | Unit | Notes | |---|---|---| | Temperature | °C | Air temperature at local standard noon | | Relative humidity | % | At noon, 0–100 | | Wind speed | km/h | At 10 m height, at noon. Convert m/s × 3.6 | | Rain | mm | Accumulated over the previous 24 hours (noon to noon) | Plus the **month**, which sets the day length. Longer days dry the deeper fuel layers faster. > Why noon? The system was calibrated on noon observations, which are a good > proxy for the mid-afternoon peak of fire danger. Feeding it daily maxima or > daily means will give different, uncalibrated numbers. ## Three layers of fuel, three memories Imagine digging into a forest floor. You go through three layers, and each one dries at its own speed. | Layer | Code | Typical depth | Time to lose ~2/3 of its excess moisture | |---|---|---|---| | Litter: dead needles, leaves, grass | **FFMC** (Fine Fuel Moisture Code) | top 1–2 cm | **~16 hours** | | Duff: loose, decomposing organic matter | **DMC** (Duff Moisture Code) | 5–10 cm | **~12 days** | | Deep, compact organic soil | **DC** (Drought Code) | 10–20 cm | **~52 days** | Each code is a **number where higher means drier**: - **FFMC** runs from 0 to 101. Above ~85 fine fuels ignite easily, and above ~90 almost any spark will catch. - **DMC** starts near 0 after snowmelt and can pass 100 in a dry summer. - **DC** starts near 15 in spring and can pass 600–800 in a long drought. ### Rain has to get through the canopy first Light rain is caught by the trees and never reaches the fuel. Each code has a threshold below which rain is ignored: | Code | Rain ignored below | |---|---| | FFMC | 0.5 mm | | DMC | 1.5 mm | | DC | 2.8 mm | ### The memory, visualised The chart below starts from mid-summer conditions, adds a 40 mm storm, then follows three weeks of hot, dry days. It shows how much of the storm's wetting each code has "undone". ![Recovery after a storm](images/memory.svg) - **FFMC** is back to pre-storm dryness in **2 days**. Fine fuel reacts to today. - **DMC** takes about **a week**. - **DC** takes **more than two weeks**, and it would take longer outside July. That is why a summer drought keeps fires deep-burning even after a rainy day. ## Why it is a chain Each moisture code is computed **from yesterday's value plus today's weather**: ``` FFMC(today) = f(FFMC(yesterday), temperature, humidity, wind, rain) DMC(today) = g(DMC(yesterday), temperature, humidity, rain, month) DC(today) = h(DC(yesterday), temperature, rain, month) ``` So you cannot compute the FWI for 15 August from 15 August's weather alone. You need the whole season leading up to it. That is what "chain" means, and it has a practical consequence: **you must store the state** (the three codes) from one day to the next. At the start of the season (after snowmelt, or in early spring in climates without snow) the chain starts from standard values: **FFMC 85, DMC 6, DC 15**. These are `STANDARD_PARAMS.initial_state`. They are deliberately "neutral", and the codes need weeks of real weather before they mean much. The next chart shows what happens if you restart from them in the middle of summer: ![Cold restart compared with a continuous chain](images/restart.svg) The restarted chain (grey) underestimates the Drought Code by 95 to 465 points for the rest of the season, and the FWI by up to 48 points in the first weeks. **Never restart a chain mid-season.** Persist the state instead (see the [cookbook](cookbook.md#persist-the-state-between-runs)). ## From codes to indices The three codes are combined into three indices: ### ISI: Initial Spread Index, *how fast would it run?* ISI combines **FFMC** with **wind**. Wind is the single biggest driver of spread rate: at FFMC 92, going from calm to 40 km/h multiplies ISI by more than seven. ``` wind (km/h) 0 10 20 30 40 50 60 ISI 5.7 9.4 15.6 25.8 42.8 70.8 117.2 ``` ### BUI: Buildup Index, *how much fuel is there to burn?* BUI combines **DMC** and **DC**. It answers how much of the fuel bed is dry enough to burn, which also predicts how hard a fire will be to mop up. ### FWI: Fire Weather Index, *how intense would the fire be?* FWI combines **ISI** and **BUI** into the single number that goes on fire danger maps. It is unbounded in principle. In practice, values above 50 are extreme in most of Europe, and Canadian and Australian summers can reach 100 or more. ## Danger classes The FWI is a continuous number. Agencies translate it into classes calibrated for their region. EFFIS, for example, uses these for Europe: | Class | FWI | |---|---| | Low | < 11.2 | | Moderate | 11.2 – 21.3 | | High | 21.3 – 38.0 | | Very high | 38.0 – 50.0 | | Extreme | 50.0 – 70.0 | | Very extreme | > 70.0 | Since 1.2 `effis_class(fwi)` gives this class, with the boundaries as EFFIS publishes them ("very extreme" was added in June 2021). A class is a convention: for your own, [example 02](https://github.com/agent-engineering-studio/fwi-chain/blob/main/examples/02_fire_season.py) shows the five lines it takes. Whether a value is rare in a place is a different question: see the climatology in the [API reference](api.md). ![FWI through a fire season](images/fire-season.svg) ## A worked example by hand The Drought Code on a dry day is simple enough to check with a pencil. Start from DC = 15 on an April day at 17 °C with no rain. Van Wagner's Eq. 22 gives the potential evapotranspiration, with the April day-length factor 0.9: ``` PE = (0.36 × (T + 2.8) + Lf) / 2 = (0.36 × (17 + 2.8) + 0.9) / 2 = 4.014 DC(today) = DC(yesterday) + PE = 15 + 4.014 = 19.014 ``` And the library agrees: ```python >>> from fwi_chain import drought_code >>> drought_code(15.0, temperature_c=17.0, rain_24h_mm=0.0, day_length=0.9) 19.014 ``` That is exactly the DC of the reference day in [Validation](validation.md). ## How the code maps to the science Every function in [`src/fwi_chain/chain.py`](https://github.com/agent-engineering-studio/fwi-chain/blob/main/src/fwi_chain/chain.py) is annotated with the equation numbers of Van Wagner (1987): | Function | Equations | Inputs | |---|---|---| | `fine_fuel_moisture_code` | 1–10 | previous FFMC, T, RH, wind, rain | | `duff_moisture_code` | 11–17 | previous DMC, T, RH, rain, day length | | `drought_code` | 18–23 | previous DC, T, rain, day length | | `initial_spread_index` | 24–26 | FFMC, wind | | `buildup_index` | 27–28 | DMC, DC | | `fire_weather_index` | 29–31 | ISI, BUI | | `advance` | all | yesterday's `FwiState` + today's weather | ## Further reading - Van Wagner, C.E. (1987). *Development and structure of the Canadian Forest Fire Weather Index System*. Forestry Technical Report 35, Canadian Forestry Service. - Natural Resources Canada, *Canadian Wildland Fire Information System*: background on the FWI System. - EFFIS, *European Forest Fire Information System*: daily FWI forecasts for Europe. - [`cffdrs`](https://cran.r-project.org/package=cffdrs): the reference R implementation. # Getting started This guide takes you from `pip install` to a daily job that keeps the chain running all season. Allow about ten minutes. ## 1. Install ```bash pip install fwi-chain # or uv add fwi-chain ``` Python 3.12 or newer. There are no dependencies to install. ## 2. Compute one day ```python from fwi_chain import STANDARD_PARAMS, advance out = advance( STANDARD_PARAMS.initial_state, month=4, temperature_c=17.0, relative_humidity_pct=42.0, wind_speed_kmh=25.0, rain_24h_mm=0.0, params=STANDARD_PARAMS, ) ``` `out` is an `FwiOutputs`: ```python >>> out FwiOutputs(state=FwiState(ffmc=87.69..., dmc=8.545..., dc=19.014), isi=10.85..., bui=8.49..., fwi=10.09...) ``` - `out.state` holds the **three moisture codes**, which is what you carry to tomorrow. - `out.isi`, `out.bui` and `out.fwi` are **today's indices**, which is what you publish. All arguments after `state` are **keyword-only**, and every name carries its unit. That makes it hard to pass wind in m/s by mistake. The call fails loudly if you forget an argument. ## 3. Run a season The chain is a fold over days. Each day's output state is the next day's input: ```python import csv from datetime import date from fwi_chain import STANDARD_PARAMS, advance state = STANDARD_PARAMS.initial_state with open("noon_weather.csv") as f: # date,temp_c,rh_pct,wind_kmh,rain_mm for row in csv.DictReader(f): day = date.fromisoformat(row["date"]) out = advance( state, month=day.month, temperature_c=float(row["temp_c"]), relative_humidity_pct=float(row["rh_pct"]), wind_speed_kmh=float(row["wind_kmh"]), rain_24h_mm=float(row["rain_mm"]), params=STANDARD_PARAMS, ) state = out.state print(day, f"FWI {out.fwi:5.1f}") ``` Try the bundled version with synthetic weather: ```bash git clone https://github.com/agent-engineering-studio/fwi-chain cd fwi-chain python examples/02_fire_season.py season.csv # needs `pip install fwi-chain` or `uv run` ``` ## 4. Keep the state between runs In production you usually run once a day, when the noon observation (or the forecast) arrives. The process ends, so the state has to live somewhere: ``` ┌─────────────┐ load ┌──────────┐ advance() ┌──────────┐ save ┌─────────────┐ │ storage │ ────────▶ │ FwiState │ ────────────▶ │ FwiState │ ───────▶ │ storage │ │ (yesterday) │ └──────────┘ + today's └──────────┘ │ (today) │ └─────────────┘ weather └─────────────┘ ``` `FwiState` is a frozen dataclass of three floats, so it is easy to store anywhere: ```python import dataclasses, json from fwi_chain import FwiState saved = json.dumps(dataclasses.asdict(out.state)) # '{"ffmc": 87.69..., "dmc": ..., "dc": ...}' state = FwiState(**json.loads(saved)) # tomorrow ``` [Example 03](https://github.com/agent-engineering-studio/fwi-chain/blob/main/examples/03_daily_job_sqlite.py) is a complete daily job backed by SQLite. Run it a few times and watch it resume from where it left off. ## 5. Adapt the parameters to your region `STANDARD_PARAMS` uses Van Wagner's day-length tables for **46°N**, which suits most of Europe, southern Canada and the northern United States. The tables matter for DMC and DC only. For other regions, build your own `FwiParams`: ```python from fwi_chain import STANDARD_PARAMS, FwiParams def shift_six_months(t): # a common approximation for the southern hemisphere return t[6:] + t[:6] SOUTH = FwiParams( ffmc_start=85.0, dmc_start=6.0, dc_start=15.0, day_length_dmc=shift_six_months(STANDARD_PARAMS.day_length_dmc), day_length_dc=shift_six_months(STANDARD_PARAMS.day_length_dc), ) ``` Near the equator, or at high latitudes, use tables adjusted for your band. The `cffdrs` R package documents several. See [example 05](https://github.com/agent-engineering-studio/fwi-chain/blob/main/examples/05_southern_hemisphere.py). ## Common mistakes | Mistake | Symptom | Fix | |---|---|---| | Wind in **m/s** instead of km/h | FWI far too low on windy days | multiply by 3.6 | | Daily **max** temperature / **min** humidity instead of noon values | FWI biased high | use noon observations (or a forecast valid at local noon) | | Rain over the calendar day instead of **noon to noon** | wetting attributed to the wrong day | accumulate rain from yesterday's noon to today's noon | | **Restarting** the chain from 85/6/15 every run | DC and BUI stay near zero all summer | persist `out.state` and load it tomorrow | | **Skipping** days with missing data | the codes jump, because one call = one day | fill gaps with an estimate (nearest station, forecast) rather than skipping | | Relative humidity as a **fraction** (0.42) | FFMC far too high | pass percent (42) | | Unordered rows | nonsense values | sort by date before running the chain | ## Next steps - [Cookbook](cookbook.md): pandas, many stations, parallelism, an HTTP service. - [API reference](api.md): every function and its arguments. - [How the FWI works](how-fwi-works.md): the science behind the numbers. # Cookbook Short, copy-pasteable recipes for common tasks. `fwi-chain` itself has no dependencies. Where a recipe uses pandas or FastAPI, that is your choice, not a requirement. - [Persist the state between runs](#persist-the-state-between-runs) - [Run the chain over a pandas DataFrame](#run-the-chain-over-a-pandas-dataframe) - [Many stations or grid cells](#many-stations-or-grid-cells) - [Use all CPU cores](#use-all-cpu-cores) - [Convert units](#convert-units) - [Danger classes](#danger-classes) - [Daily Severity Rating (DSR)](#daily-severity-rating-dsr) - [Missing days](#missing-days) - [Run on a forecast](#run-on-a-forecast) - [Serve it over HTTP](#serve-it-over-http) - [What-if analysis](#what-if-analysis) --- ## Persist the state between runs The state is three floats. Store it however you like. **JSON file** ```python import dataclasses, json from pathlib import Path from fwi_chain import STANDARD_PARAMS, FwiState path = Path("state.json") state = FwiState(**json.loads(path.read_text())) if path.exists() else STANDARD_PARAMS.initial_state # ... out = advance(state, ...) ... path.write_text(json.dumps(dataclasses.asdict(out.state))) ``` **SQL table** (one row per station per day; keeping history makes reruns easy) ```sql CREATE TABLE fwi_state ( station TEXT NOT NULL, day DATE NOT NULL, ffmc REAL, dmc REAL, dc REAL, isi REAL, bui REAL, fwi REAL, PRIMARY KEY (station, day) ); ``` The full daily job is [`examples/03_daily_job_sqlite.py`](https://github.com/agent-engineering-studio/fwi-chain/blob/main/examples/03_daily_job_sqlite.py). **Redis / key-value cache** ```python r.hset(f"fwi:{station}", mapping=dataclasses.asdict(out.state)) state = FwiState(**{k.decode(): float(v) for k, v in r.hgetall(f"fwi:{station}").items()}) ``` --- ## Run the chain over a pandas DataFrame The chain is sequential in time, so iterate rows in date order and collect the results. ```python import pandas as pd from fwi_chain import STANDARD_PARAMS, advance df = pd.read_csv("noon.csv", parse_dates=["date"]).sort_values("date") state = STANDARD_PARAMS.initial_state records = [] for row in df.itertuples(index=False): out = advance( state, month=row.date.month, temperature_c=row.temp_c, relative_humidity_pct=row.rh_pct, wind_speed_kmh=row.wind_kmh, rain_24h_mm=row.rain_mm, params=STANDARD_PARAMS, ) state = out.state records.append( { "ffmc": out.state.ffmc, "dmc": out.state.dmc, "dc": out.state.dc, "isi": out.isi, "bui": out.bui, "fwi": out.fwi, } ) df = df.join(pd.DataFrame(records, index=df.index)) ``` With a `station` column, run the same loop per group: ```python def run_chain(group: pd.DataFrame) -> pd.DataFrame: ... # the loop above, on `group` return group.join(pd.DataFrame(records, index=group.index)) df = pd.concat(run_chain(g) for _, g in df.sort_values("date").groupby("station")) ``` > For large gridded datasets (NetCDF, Zarr), a vectorised implementation such as > [xclim](https://github.com/Ouranosinc/xclim) will be faster than a Python loop. > `fwi-chain` is designed for row-at-a-time pipelines: databases, streams, services. --- ## Many stations or grid cells Locations are independent, so keep a mapping from location to state: ```python states: dict[str, FwiState] = load_states() # from your storage for station_id, obs in todays_observations.items(): prev = states.get(station_id, STANDARD_PARAMS.initial_state) out = advance( prev, month=today.month, params=STANDARD_PARAMS, temperature_c=obs.t, relative_humidity_pct=obs.rh, wind_speed_kmh=obs.wind, rain_24h_mm=obs.rain, ) states[station_id] = out.state publish(station_id, today, out.fwi) save_states(states) ``` See [`examples/04_many_stations.py`](https://github.com/agent-engineering-studio/fwi-chain/blob/main/examples/04_many_stations.py). --- ## Use all CPU cores Each location's season is independent. Spread locations, not days, across processes: ```python from concurrent.futures import ProcessPoolExecutor from fwi_chain import STANDARD_PARAMS, advance def run_season(readings): # one location, all days in order state, fwi = STANDARD_PARAMS.initial_state, [] for r in readings: out = advance( state, month=r.day.month, params=STANDARD_PARAMS, temperature_c=r.temperature_c, relative_humidity_pct=r.relative_humidity_pct, wind_speed_kmh=r.wind_speed_kmh, rain_24h_mm=r.rain_24h_mm, ) state = out.state fwi.append(out.fwi) return fwi if __name__ == "__main__": with ProcessPoolExecutor() as pool: results = list(pool.map(run_season, readings_per_location, chunksize=64)) ``` One `advance` call is a few microseconds of pure arithmetic, so a single core handles a full season for thousands of locations in seconds. --- ## Convert units | You have | `fwi-chain` wants | Conversion | |---|---|---| | wind in m/s | km/h | `kmh = ms * 3.6` | | wind in knots | km/h | `kmh = kn * 1.852` | | temperature in K | °C | `c = k - 273.15` | | temperature in °F | °C | `c = (f - 32) / 1.8` | | RH as a fraction | % | `pct = frac * 100` | | rain in inches | mm | `mm = inch * 25.4` | | precipitation in m (e.g. ERA5 `tp`) | mm | `mm = m * 1000` | | dew point + temperature | RH % | Magnus formula: `100 * exp(17.625*td/(243.04+td)) / exp(17.625*t/(243.04+t))` | --- ## Danger classes The EFFIS classes for Europe are in the library: `effis_class(fwi)`. Classes are regional; for your own, the same five lines with your thresholds: ```python DANGER_CLASSES = [ (70.0, "very extreme"), (50.0, "extreme"), (38.0, "very high"), (21.3, "high"), (11.2, "moderate"), (0.0, "low"), ] def danger_class(fwi: float) -> str: return next(label for lower, label in DANGER_CLASSES if fwi >= lower) ``` --- ## Daily Severity Rating (DSR) DSR is a transformation of FWI that scales with the effort needed to control a fire. It is commonly averaged over a season (the Seasonal Severity Rating): ```python def daily_severity_rating(fwi: float) -> float: return 0.0272 * fwi**1.77 ``` --- ## Missing days One call to `advance` is **one day**. If a day's observation is missing, skipping it compresses two days of drying into one step, and calling `advance` twice with the same weather double-counts. Prefer, in order: 1. a nearby station, or a weather-model analysis for that day; 2. a forecast that was valid for that day; 3. a conservative estimate (for example yesterday's temperature and humidity, no rain); and flag the output as estimated. Do not reset the state. --- ## Run on a forecast To forecast danger for the next *N* days, start from today's **observed** state and advance it through the forecast. Do **not** save the forecast states as the real chain: ```python state = load_observed_state(station) # the real chain, up to today for day in forecast_days: # tomorrow, the day after, ... out = advance(state, month=day.date.month, params=STANDARD_PARAMS, ...) state = out.state # local only: never persisted print(day.date, out.fwi) ``` Tomorrow, when the observation arrives, advance the **observed** state again. --- ## Serve it over HTTP A tiny stateless endpoint with FastAPI. The client sends yesterday's state and today's weather and gets back today's outputs: ```python from dataclasses import asdict from fastapi import FastAPI from pydantic import BaseModel from fwi_chain import STANDARD_PARAMS, FwiState, advance app = FastAPI() class Request(BaseModel): ffmc: float = 85.0 dmc: float = 6.0 dc: float = 15.0 month: int temperature_c: float relative_humidity_pct: float wind_speed_kmh: float rain_24h_mm: float @app.post("/fwi") def fwi(req: Request) -> dict: out = advance( FwiState(req.ffmc, req.dmc, req.dc), month=req.month, temperature_c=req.temperature_c, relative_humidity_pct=req.relative_humidity_pct, wind_speed_kmh=req.wind_speed_kmh, rain_24h_mm=req.rain_24h_mm, params=STANDARD_PARAMS, ) return {**asdict(out.state), "isi": out.isi, "bui": out.bui, "fwi": out.fwi} ``` ```bash curl -s localhost:8000/fwi -H 'content-type: application/json' \ -d '{"month":4,"temperature_c":17,"relative_humidity_pct":42,"wind_speed_kmh":25,"rain_24h_mm":0}' # {"ffmc":87.69...,"dmc":8.545...,"dc":19.014,"isi":10.85...,"bui":8.49...,"fwi":10.09...} ``` --- ## What-if analysis The six equations are exported individually, so you can explore sensitivity without running a season: ```python from fwi_chain import initial_spread_index, fire_weather_index for wind in range(0, 70, 10): isi = initial_spread_index(92.0, wind_speed_kmh=wind) print(wind, round(fire_weather_index(isi, 80.0), 1)) ``` See [`examples/06_individual_equations.py`](https://github.com/agent-engineering-studio/fwi-chain/blob/main/examples/06_individual_equations.py). # Facts, what moved the index, and the MCP server *New in 1.2.* The rule of everything on this page: **the numbers come from the chain; a model may explain them, never invent them.** !!! warning "A fire weather index is not an alert" It says how easily a fire would start and spread in the weather given, not that one will. The official fire danger for Europe is published by [EFFIS](https://forest-fire.emergency.copernicus.eu/); in Italy the fire danger bulletin is issued by the Dipartimento della Protezione Civile and by the regions. ## What moved the index On 7 May 1985, in the test series of `cffdrs`, the FWI went from 21.7 to 52.6. `explain_change` takes the two days apart: ```python from fwi_chain import STANDARD_PARAMS, explain_change e = explain_change(walked[i - 1], walked[i], params=STANDARD_PARAMS) # FWI 21.7 -> 52.6 (+30.9) # the chain's memory +1.2 # wind +18.0 12 -> 27 km/h # humidity +11.1 33 -> 17 % # temperature +0.6 27 -> 28 °C # rain +0.0 ``` Two parts. **The chain's memory** (`carry_over`): with the very same weather as the day before, the index would still have moved, because fuel that is drying keeps drying. **The weather** (`weather`): what the change in the four readings did, split among them. The readings act together (wind matters more on dry fuel), so the split is a choice. The one used is the Shapley value: the effect of a reading is its average effect over every order in which the four could have changed. It is the split in which the four effects add up exactly, and it costs 16 runs of the equations. Removing one reading at a time, the obvious alternative, was tried first: on a constructed day with a storm after dry weather it left 14 of 21.6 points assigned to no reading. What it is not: it says what moved the number, not why the weather changed, and nothing about fires. ## The answers as facts `fwi_chain.facts` gives the same answers as plain `dict`s, ready for JSON, with the units in the key names (`_c`, `_pct`, `_kmh`, `_mm`, `_days`; the six codes have no unit) and the rule in every answer. | Function | What it gives | |---|---| | `day_facts(day, *, previous=None, params=None, month_quantiles=None, spinup_days=None)` | one walked day: readings, six codes, EFFIS class, `chain_days`; with `previous`, what moved the FWI; with `month_quantiles`, its percentile; with `spinup_days`, whether the chain is `settled` | | `walk_facts(walked, *, params, quantiles_by_month=None, spinup_days=None)` | a stretch: every day, the peak, the rain, days per class, the last day in full | | `distribution_facts(values, *, value=None)` | a list of FWI values as 21 quantiles, and where `value` falls | Codes and effects are rounded to one decimal, as fire services publish them. Rounded parts may not add up to the rounded total by 0.1. ## Checking a text `fwi_chain.check.check_text(text, facts, *, question="")` returns the numbers of a text that are not facts as written: | Fault | Example, when the facts say 12.4 mm of rain and an FWI of 52.6 | |---|---| | `unit` | "12.4 %", "an FWI of 52.6 km/h" | | `rounded` | "12.5 mm" | | `invented` | "gusts of 77 km/h" | ```python from fwi_chain.check import check_text check_text("The wind rose to 27 % and added 18.5 points.", facts) # [Misquote(text='27 %', unit='pct', fault='unit', nearest='observation.wind_speed_kmh = 27 kmh'), # Misquote(text='18.5', unit=None, fault='invented', nearest=None)] ``` Its limits, measured on the [faithfulness set](benchmark.md#the-faithfulness-set): it knows a number is a fact of the right unit, not that it is said of the right thing; and against the facts of a whole series a small invented integer can pass by chance. Check a text against the facts of the day it is about. ## The MCP server ```bash pip install "fwi-chain[mcp]" fwi-chain-mcp # standard input and output fwi-chain-mcp --http # streamable HTTP, http://127.0.0.1:8772/mcp ``` The package itself still needs nothing: `mcp` is an extra, and only `fwi_chain.mcp_server` imports it. The tools compute only from what a call gives them: no network, no weather of their own, no clock. | Tool | What it answers | |---|---| | `walk` | the chain over the noon readings given: every day, the peak, the last day with what moved it | | `explain` | one day of that stretch, taken apart; with past values of the month, its percentile | | `percentile` | where an FWI falls among the values of its place and month | | `check` | the numbers of a text that are not facts of a tool's answer | A reading is `[day, temperature_c, relative_humidity_pct, wind_speed_kmh, rain_24h_mm]`. A value `null` means the day was not measured: it is skipped, never zeroed. For a client such as Claude Desktop: ```json { "mcpServers": { "fwi-chain": { "command": "fwi-chain-mcp" } } } ``` ## For agents that write code The site serves [`llms.txt`](https://agentengineering.it/fwi-chain/llms.txt), the whole documentation as one text ([`llms-full.txt`](https://agentengineering.it/fwi-chain/llms-full.txt)) and an [agent skill](https://agentengineering.it/fwi-chain/skills/fwi-chain/SKILL.md) with the recipe and the traps. # Notebooks, the page and Docker ## Seven notebooks All run with no network. | Notebook | What it shows | |---|---| | `01_single_day` | one day of the chain, the six outputs | | `02_fire_season` | a whole season day by day, the danger classes, a CSV | | `03_daily_job_sqlite` | a daily job that stores the state and resumes | | `04_many_stations` | one state per station | | `05_southern_hemisphere` | day-length tables for another latitude | | `06_individual_equations` | the equations one by one | | `07_what_moved_the_index` | 48 days of the cffdrs test series; one day taken apart; a sentence checked against the facts | They are in [`notebooks/`](https://github.com/agent-engineering-studio/fwi-chain/tree/main/notebooks). Notebooks 01 to 06 are the scripts of `examples/`, cell by cell. ```bash uv run --group examples jupyter lab notebooks/ make notebooks # write them from the examples, run them all, save the results ``` ## The page for a public body `app/` is a small page in Italian, "Il diario del pericolo d'incendio": the chain of one place, day by day, from the weather the body gives, and what moved the index on the day chosen. See [Riuso](riuso.md). ```bash make demo # http://127.0.0.1:3007 (needs uv and npm) ``` ## Docker Nothing to install but Docker: ```bash docker compose up # the page on :3007, the notebooks on :8885 docker compose --profile mcp up mcp # the MCP server on :8772/mcp docker compose run --rm bench # the benchmark make down # stop and remove everything ``` | Service | Container | Port | Variable | |---|---|---|---| | the page | `fwi-chain-ui` | 3007 | `FWI_CHAIN_PORT` | | the notebooks | `fwi-chain-notebooks` | 8885 | `FWI_CHAIN_NOTEBOOKS_PORT` | | the MCP server | `fwi-chain-mcp` | 8772 | `FWI_CHAIN_MCP_PORT` | Every port listens on `127.0.0.1` only. `make help` lists every target. # FAQ ### What is the FWI, in one sentence? A number, computed every day from noon weather, that estimates how intense a wildfire would be if one started. It is the core output of the Canadian Forest Fire Weather Index System, used by fire agencies worldwide and by EFFIS for Europe. ### Is this an official implementation? No. It is an independent transcription of Van Wagner (1987), measured against the 48-day test series of the `cffdrs` R package: at most 0.25 FWI points apart, the same danger class every day. See [Validation](validation.md). ### How does it compare with `cffdrs` and `xclim`? | | fwi-chain | cffdrs | xclim | |---|---|---|---| | Language | Python | R | Python | | Dependencies | none | R + packages | NumPy, xarray, … | | Unit of work | one location, one day | data frames | gridded arrays | | State between days | explicit value you persist | inside the data frame | inside the time dimension | | Best for | services, databases, streams, teaching | research in R | climate grids, NetCDF | They answer the same equations, with one known difference: `cffdrs` follows the constants of the 1985 FORTRAN program, this library the 1987 report as printed. `CFFDRS_PARAMS` takes the program's constants: then the six codes match cffdrs to 0.006. See [Validation](validation.md). Pick the one that fits your pipeline. ### Why should I persist the state? Can't I just start from 85 / 6 / 15 every day? No. DMC and DC remember weeks of weather. Restarting throws that memory away and underestimates danger. With the synthetic season in the docs, a 1 July restart underestimates the FWI by up to 48 points for weeks. See [How the FWI works](how-fwi-works.md#why-it-is-a-chain). ### When does the season start? Traditionally the chain starts three days after snowmelt, or when noon temperatures have stayed above about 12 °C for three days in climates without snow. It starts from the standard codes, or from an overwintered DC if you track one. Many Mediterranean services simply run the chain all year round. ### Can I use daily maximum temperature and minimum humidity? You can, but the system was calibrated on noon values. Daily extremes produce systematically higher, uncalibrated numbers. A forecast or reanalysis valid at local noon is the right input. ### Does it work in the southern hemisphere / the tropics / the Arctic? The equations do. The **day-length tables** must match your latitude: `STANDARD_PARAMS` is for 46°N. Pass your own `FwiParams`, as in [example 05](https://github.com/agent-engineering-studio/fwi-chain/blob/main/examples/05_southern_hemisphere.py). ### Does it compute danger classes? Deliberately not. Classes are a regional policy choice. Example 02 and the [cookbook](cookbook.md#danger-classes) show the EFFIS classes in five lines. ### Is it fast enough for a whole country? One call takes a few microseconds. A full 214-day season for 1,000 locations takes about a second and a half on one core, and locations parallelise trivially. For multi-gigabyte climate grids, a vectorised library (xclim) is the better tool. ### Can I use it commercially? Yes. It is Apache-2.0. ### Where did it come from? It was extracted from [Limen](https://github.com/agent-engineering-studio/limen), where it computes wildfire danger for every ~9 km weather node in Italy. ### How can I help? See [CONTRIBUTING.md](https://github.com/agent-engineering-studio/fwi-chain/blob/main/CONTRIBUTING.md). Reference vectors, latitude tables, docs and translations are especially welcome. # API reference Everything is importable from the top-level package: ```python from fwi_chain import ( advance, FwiState, FwiOutputs, FwiParams, STANDARD_PARAMS, CFFDRS_PARAMS, fine_fuel_moisture_code, duff_moisture_code, drought_code, initial_spread_index, buildup_index, fire_weather_index, # many days (1.1) walk_chain, days_to_walk, writable_days, rewalk_with_rain, correct_rain, NoonObservation, ChainPoint, ChainDay, catch_up, start_is_stale, # the noon reading from hourly weather (1.3) noon_reading, noon_readings, HourlySample, NoonReading, # climatology (1.1) quantiles, percentile, node_ceiling, accumulate_monthly, coverage_is_valid, QUANTILE_LEVELS, # classes and what moved the index (1.2) effis_class, EFFIS_FWI_CLASSES, explain_change, Explanation, Driver, ) ``` The facts, the text check and the MCP server are in their own modules (`fwi_chain.facts`, `fwi_chain.check`, `fwi_chain.mcp_server`): see [Facts, explanation and MCP](ai.md). All functions are **pure**: no I/O, no global state, no clock. They are safe to call from any thread or process. Weather arguments are **keyword-only** and carry their unit in the name. --- ## The chain ### `advance(state, *, month, temperature_c, relative_humidity_pct, wind_speed_kmh, rain_24h_mm, params) -> FwiOutputs` Runs **one day** of the chain: yesterday's codes plus today's noon reading. | Argument | Type | Meaning | |---|---|---| | `state` | `FwiState` | yesterday's FFMC, DMC and DC (or `params.initial_state` on day one) | | `month` | `int` | 1–12. Selects the day-length factors. Raises `ValueError` outside that range | | `temperature_c` | `float` | noon air temperature, °C | | `relative_humidity_pct` | `float` | noon relative humidity, %. Values outside 0–100 are clamped | | `wind_speed_kmh` | `float` | noon 10 m wind speed, km/h. Negative values are treated as 0 | | `rain_24h_mm` | `float` | rain accumulated over the previous 24 h, mm | | `params` | `FwiParams` | start-up codes and day-length tables. Usually `STANDARD_PARAMS` | Returns an `FwiOutputs`. ```python out = advance( state, month=7, temperature_c=31, relative_humidity_pct=22, wind_speed_kmh=18, rain_24h_mm=0, params=STANDARD_PARAMS, ) state = out.state ``` --- ## Data types All three are `@dataclass(frozen=True, slots=True)`: immutable, hashable, cheap, and serialisable with `dataclasses.asdict`. ### `FwiState` The three recursive codes carried from one day to the next. | Field | Range | Meaning | |---|---|---| | `ffmc` | 0–101 | Fine Fuel Moisture Code | | `dmc` | ≥ 0 | Duff Moisture Code | | `dc` | ≥ 0 | Drought Code | ### `FwiOutputs` A day's full result. | Field | Type | Meaning | |---|---|---| | `state` | `FwiState` | today's codes, which become tomorrow's input | | `isi` | `float` | Initial Spread Index | | `bui` | `float` | Buildup Index | | `fwi` | `float` | Fire Weather Index | ### `FwiParams` What a deployment may choose, as opposed to the constants Van Wagner fixed. | Field | Type | Meaning | |---|---|---| | `ffmc_start` | `float` | FFMC at the start of the season | | `dmc_start` | `float` | DMC at the start of the season | | `dc_start` | `float` | DC at the start of the season | | `day_length_dmc` | `tuple[float, ...]` | 12 monthly DMC day-length factors, **January first** | | `day_length_dc` | `tuple[float, ...]` | 12 monthly DC day-length adjustments, **January first** | | `constants` | `"1987"` or `"cffdrs"` | which printing of two constants. Default `"1987"` (since 1.4.0) | - `initial_state` (property) returns `FwiState(ffmc_start, dmc_start, dc_start)`. - The constructor raises `ValueError` if a table does not have exactly 12 entries. An 11-entry table would otherwise shift the whole year silently. It raises `ValueError` too for a `constants` that is neither `"1987"` nor `"cffdrs"`. **`constants`.** The 1987 report and the FORTRAN program of Van Wagner & Pickett (1985) print two constants differently: | | `"1987"`: the report (default) | `"cffdrs"`: the 1985 program | |---|---|---| | FFMC scale (Eq. 1, 10, and the ISI) | 147.2 | 147.27723 | | DMC wetting (Eq. 12) | `exp(5.6348 - P / 43.43)` | `280 / exp(0.023 P)` | The `cffdrs` R package follows the program. Over its 48-day test series, with `"1987"` the FWI is at most 0.254 points from cffdrs; with `"cffdrs"` every code is within 0.006, the rounding of cffdrs's own output. The class is the same on all 48 days either way ([benchmark](benchmark.md)). Walk one chain with one printing from start to end: a stored state carries its digits. The facts (`fwi_chain.facts`) and the MCP tools name the printing in `constants`. ### `STANDARD_PARAMS` Van Wagner's published defaults: start-up codes 85 / 6 / 15 and the day-length tables for 46°N (Tables 2 and 3 of the 1987 report), with `constants="1987"`. ### `CFFDRS_PARAMS` `STANDARD_PARAMS` with `constants="cffdrs"`: the same start-up codes and tables, the constants of the 1985 program. Use it to match cffdrs's digits. | Month | J | F | M | A | M | J | J | A | S | O | N | D | |---|---|---|---|---|---|---|---|---|---|---|---|---| | `day_length_dmc` | 6.5 | 7.5 | 9.0 | 12.8 | 13.9 | 13.9 | 12.4 | 10.9 | 9.4 | 8.0 | 7.0 | 6.0 | | `day_length_dc` | −1.6 | −1.6 | −1.6 | 0.9 | 3.8 | 5.8 | 6.4 | 5.0 | 2.4 | 0.4 | −1.6 | −1.6 | --- ## The individual equations Use these for sensitivity analysis, teaching, or a custom chain. The equation numbers refer to Van Wagner (1987). ### `fine_fuel_moisture_code(previous, *, temperature_c, relative_humidity_pct, wind_speed_kmh, rain_24h_mm, constants="1987") -> float` Eqs. 1–10. Returns today's FFMC on the 0–101 scale. Rain at or below 0.5 mm is intercepted by the canopy and ignored. ### `duff_moisture_code(previous, *, temperature_c, relative_humidity_pct, rain_24h_mm, day_length, constants="1987") -> float` Eqs. 11–17. `day_length` is the month's factor, e.g. `params.day_length_dmc[month - 1]`. Rain at or below 1.5 mm is ignored. Below −1.1 °C there is no drying. ### `drought_code(previous, *, temperature_c, rain_24h_mm, day_length) -> float` Eqs. 18–23. `day_length` is e.g. `params.day_length_dc[month - 1]`. Rain at or below 2.8 mm is ignored. Below −2.8 °C there is no drying. ### `initial_spread_index(ffmc, *, wind_speed_kmh, constants="1987") -> float` Eqs. 24–26. Expected rate of spread. This is where wind enters the chain. ### `buildup_index(dmc, dc) -> float` Eqs. 27–28. Total fuel available. Returns `0.0` when both codes are zero (a saturated landscape), where Eq. 27 would otherwise divide by zero. ### `fire_weather_index(isi, bui) -> float` Eqs. 29–31. The published index: the intensity of a spreading fire. ```python from fwi_chain import initial_spread_index, buildup_index, fire_weather_index isi = initial_spread_index(92.0, wind_speed_kmh=30.0) # 25.8 bui = buildup_index(dmc=40.0, dc=400.0) # 64.0 fwi = fire_weather_index(isi, bui) # 47.2 ``` --- ## Guarantees - **No NaN, no negatives.** Under any finite weather, from frost to a 45 °C, 120 km/h sirocco to a 200 mm cloudburst, all six outputs are finite and ≥ 0, and FFMC ≤ 101. This is tested. - **Deterministic.** The same inputs always give bit-identical outputs. - **Stable API.** The package follows [Semantic Versioning](https://semver.org/). ### `__version__` `fwi_chain.__version__` is the installed package version, read from package metadata. --- ## Many days *New in 1.1.* `advance()` is one day. These walk a chain over many, from a point you stored, and leave the storing to you. Days are `datetime.date` values you pass in: nothing reads a clock, so "today" is always an argument. ### Types | Type | Fields | Meaning | |---|---|---| | `NoonObservation` | `temperature_c`, `relative_humidity_pct`, `wind_speed_kmh`, `rain_24h_mm` | the four noon readings of one day | | `ChainPoint` | `day`, `state`, `chain_days` | a chain as of one day: where a walk resumes from | | `ChainDay` | `day`, `outputs`, `chain_days`, `observation` | one walked day. `.point` gives it back as a `ChainPoint` | `chain_days` counts the days the chain has been advanced since it last started from the standard codes. It tells a settled drought code from one still reporting its seed. ### `walk_chain(observations, days, *, start, params, max_gap_days) -> list[ChainDay]` Walks one chain over `days`. `observations` maps a day to its `NoonObservation`; `start` is the last stored `ChainPoint` before `days[0]`, or `None`. - A day with no observation is **skipped, not zeroed**. - A `start` more than `max_gap_days` before `days[0]` is discarded: the walk restarts from `params.initial_state` and `chain_days` from zero. - Days missing inside the window are not counted against `max_gap_days`. ```python from datetime import date from fwi_chain import STANDARD_PARAMS, NoonObservation, walk_chain days = [date(2026, 7, 1), date(2026, 7, 2), date(2026, 7, 3)] observations = { days[0]: NoonObservation(31, 22, 18, 0), days[2]: NoonObservation(28, 35, 10, 4.2), # 2 July is missing: skipped } walked = walk_chain(observations, days, start=None, params=STANDARD_PARAMS, max_gap_days=7) resume_from = walked[-1].point # store this; pass it as `start` next time ``` ### `days_to_walk(target, *, last_day, max_gap_days) -> list[date]` The days to walk to bring a chain up to `target`: from the day after `last_day`, never further back than `max_gap_days` before `target`. `[target]` when `last_day` is `None`. ### `catch_up(observations, target, *, start, params, max_gap_days) -> list[ChainDay]` *New in 1.2.* The daily update in one call: brings a chain up to `target`. A `start` more than `max_gap_days` before `target` is discarded, at exactly that limit, and `target` alone is walked from the standard codes; otherwise every day after `start` is walked. Use this instead of calling `days_to_walk` and then `walk_chain` yourself: that pair trims the window first and measures the gap from the trimmed window, so a state up to twice the limit old is carried on. ### `start_is_stale(start, day, *, max_gap_days) -> bool` *New in 1.2.* Whether `start` is more than `max_gap_days` before `day`. ### `writable_days(walked, *, today) -> list[ChainDay]` The walked days on or before `today`. A forecast day is worth computing and must never be stored: it would become tomorrow's predecessor. ### `rewalk_with_rain(rows, start, rain, *, params, max_gap_days) -> list[ChainDay]` Redoes `rows` from `start` with measured rain. `rain` maps a day to millimetres over the 24 h before its noon reading; a day missing from it, or mapped to `None`, keeps the row's own rain, because a hole in the measurement is not a dry day. Temperature, humidity and wind are the rows' own. Stops at the first row more than `max_gap_days` after the one before it. ### `correct_rain(series, *, since, rain, params, max_gap_days, weather=None) -> list[ChainDay]` The same, on a stored chain: restarts from the last row before `since` (or from the chain's first row, if it was born later) and returns every row after it, redone. With `weather`, a row whose day is in it takes that observation before the rain is applied. Idempotent. --- ## The noon reading *New in 1.3.* The chain wants one reading a day, at local solar noon. Weather usually comes hour by hour; these turn the hours into that reading, and say how good a reading it is. ### `HourlySample(time, temperature_c=None, relative_humidity_pct=None, wind_speed_kmh=None, rain_mm=None)` One hour of weather. `None` is "not measured", never zero: a dry hour has `rain_mm=0.0`. `rain_mm` is the rain of the hour that ends at `time`. ### `noon_reading(samples, day, *, noon_hour, max_hours_from_noon, min_rain_hours) -> NoonReading` Reads the hour of `day` nearest to `noon_hour` among those with temperature, humidity and wind (the earlier one on a tie), and sums the rain of the 24 hours up to it. | Argument | Meaning | |---|---| | `noon_hour` | 0-23, on the samples' own clock. For samples in UTC over Italy, 11 | | `max_hours_from_noon` | refuse a reading further than this from `noon_hour`; `None` accepts any hour of the day | | `min_rain_hours` | refuse a reading with fewer than this many of the 24 hours of rain measured; `0` accepts any, and missing hours then count as dry | The last two have **no default**: how much to accept is a choice. | Field of `NoonReading` | Meaning | |---|---| | `observation` | the `NoonObservation`, or `None` when refused | | `refused` | `None`, or `"no reading"`, `"too far from noon"`, `"too few hours of rain"` | | `time`, `hours_from_noon` | the hour read, and its distance from `noon_hour` | | `rain_hours`, `rain_hours_missing` | hours of rain measured, and not measured, in the 24 | | `rain_measured_mm` | the rain of the measured hours: with hours missing, a lower bound | ```python from fwi_chain import noon_readings, walk_chain, STANDARD_PARAMS readings = noon_readings(samples, days, noon_hour=11, max_hours_from_noon=2, min_rain_hours=20) observations = {d: r.observation for d, r in readings.items() if r.observation} walked = walk_chain(observations, days, start=None, params=STANDARD_PARAMS, max_gap_days=7) skipped = {d: r.refused for d, r in readings.items() if r.refused} # say why, do not zero ``` ### `noon_readings(samples, days, *, noon_hour, max_hours_from_noon, min_rain_hours) -> dict[date, NoonReading]` The same for many days, reading the samples once. --- ## Climatology *New in 1.1.* Where an FWI falls in the distribution of its place and its month. ### `QUANTILE_LEVELS` `(0.0, 5.0, …, 100.0)`: the 21 levels every function here uses. ### `quantiles(values) -> list[float]` The 21 quantiles of `values`, linearly interpolated between ranks. Raises `ValueError` on an empty sequence. ### `percentile(value, q) -> float` The percentile (0–100) of `value` among the 21 quantiles `q`. 0 or 100 outside the distribution. On a flat stretch, such as a winter month with many days at FWI 0, it returns the centre of the stretch. ```python from fwi_chain import percentile, quantiles q = quantiles(august_fwi_values) # years of 1–31 August, for one place percentile(41.0, q) # e.g. 92.5: a rare day here ``` ### `node_ceiling(per_month, *, quantile, months, minimum, maximum) -> float | None` A place's "full" FWI: the mean over `months` of the monthly quantile at level `quantile`, kept between `minimum` and `maximum`. `per_month` maps a month (1–12) to its 21 quantiles. `None` when none of `months` has them. ### `accumulate_monthly(observations, days, per_month, *, state, days_walked, params, spinup_days) -> tuple[FwiState, int]` Advances the chain over `days` and **appends** each day's FWI to `per_month[month]`, a dict you own. Returns the new state and day count, to pass back in for the next stretch. The first `spinup_days` walked days move the chain but stay out of the distribution. ### `coverage_is_valid(observed, days, *, max_gap_days, min_fraction=0.95) -> bool` Whether a stretch of days has enough observations to enter a climatology: at least `min_fraction` of them, and no run of missing days longer than `max_gap_days`. --- ## Danger classes *New in 1.2.* ### `effis_class(fwi) -> str` The fire danger class EFFIS maps an FWI in: `"low"`, `"moderate"`, `"high"`, `"very high"`, `"extreme"`, `"very extreme"`. A boundary belongs to the class above it. Raises `ValueError` for a negative or non-finite FWI. ### `EFFIS_FWI_CLASSES` `((0.0, "low"), (11.2, "moderate"), (21.3, "high"), (38.0, "very high"), (50.0, "extreme"), (70.0, "very extreme"))`: each class with the FWI it starts at, as EFFIS publishes them. --- ## What moved the index *New in 1.2.* ### `explain_change(previous, today, *, params) -> Explanation` Takes apart the difference between the FWI of two consecutive walked days. | Field of `Explanation` | Meaning | |---|---| | `fwi_yesterday`, `fwi_today`, `change` | the two values and their difference | | `carry_over` | what the chain's memory alone did: today with yesterday's weather again | | `weather` | what the change in the weather did; `change == carry_over + weather` | | `drivers` | four `Driver(input, yesterday, today, effect)`, largest effect first; the effects add up to `weather` | See [Facts, explanation and MCP](ai.md) for how the split is made. # Reference (generated) Every public name, its signature and its docstring, read from the source. The hand-written [API reference](api.md) explains the same functions with examples. ## `fwi_chain.chain` Canadian Fire Weather Index chain — Van Wagner (1987), pure functions. Six numbers computed from four daily readings taken at local noon (temperature, relative humidity, 10 m wind, rain over the previous 24 h): FFMC fine fuel moisture, memory ~2/3 day ┐ DMC duff moisture, memory ~12 days ├─ three moisture codes DC drought code, memory ~52 days ┘ ISI FFMC × wind → rate of spread BUI DMC + DC → available fuel FWI ISI + BUI → the index EFFIS publishes for Europe The three moisture codes are **recursive**: today's value is a function of yesterday's. That is the whole reason this module has a state DTO: a code started from its standard initial value needs weeks of spin-up before it means anything, so a caller running the chain day by day has to persist the state between runs. Everything here is a pure function of its arguments plus a `FwiParams`: no I/O, no clock, no configuration lookup. The numeric constants below are Van Wagner's, transcribed from the equations rather than tuned, so they are *not* parameters -- what is a parameter is anything a deployment may legitimately choose (initial codes, day-length tables), and that is what `FwiParams` carries. `STANDARD_PARAMS` holds the published defaults. One choice is about the constants after all. The 1987 report and the FORTRAN program of Van Wagner & Pickett (1985) print two of them differently: the FFMC scale (147.2 in Eq. 1 and 10, and in the ISI; 147.27723 in the program) and the DMC wetting (`exp(5.6348 - P/43.43)` in Eq. 12, `280 / exp(0.023 P)` in the program). The report is the default. `FwiParams.constants = "cffdrs"`, or `CFFDRS_PARAMS`, takes the program's, which the cffdrs R package follows: over its 48-day test series the six codes then agree with cffdrs to 0.006, against 0.25 FWI points with the report's. Reference: Van Wagner, C.E. (1987), *Development and structure of the Canadian Forest Fire Weather Index System*, Forestry Technical Report 35. Equation numbers in the comments are that report's. ### `class FwiState(ffmc: float, dmc: float, dc: float)` The three recursive codes carried from one day to the next. ### `class FwiOutputs(state: FwiState, isi: float, bui: float, fwi: float)` A day's full chain: the new state plus the three derived indices. ### `Constants` Which printing of the two constants: the 1987 report, or the 1985 program cffdrs follows. ### `class FwiParams(ffmc_start: float, dmc_start: float, dc_start: float, day_length_dmc: tuple[float, ...], day_length_dc: tuple[float, ...], constants: Constants = '1987')` What a deployment may choose, as opposed to what Van Wagner fixed. `day_length_dmc` and `day_length_dc` are the 12 monthly factors (January first) for the latitude band in use. Van Wagner tabulates them for 46°N; a deployment far from that latitude, or in the southern hemisphere, passes its own tables. `constants` is the printing of the FFMC scale and of the DMC wetting: `"1987"` (the report, the default) or `"cffdrs"` (the 1985 program). A chain is walked with one of them from start to end: a stored state carries the digits of the printing that made it. ### `STANDARD_PARAMS` Van Wagner's spring start-up codes (§4) and day-length factors for 46°N (Tables 2 and 3, January first), with the constants of the 1987 report. ### `CFFDRS_PARAMS` `STANDARD_PARAMS` with the constants of the 1985 program, as the cffdrs R package uses them. Opt in to match cffdrs's digits; the default does not change. ### `fine_fuel_moisture_code(previous: float, *, temperature_c: float, relative_humidity_pct: float, wind_speed_kmh: float, rain_24h_mm: float, constants: Constants = '1987') -> float` Eqs. 1-10. Fine fuel moisture on the 0-101 FFMC scale. `constants="cffdrs"` uses the program's 147.27723 for the report's 147.2, here and in `initial_spread_index`. ### `duff_moisture_code(previous: float, *, temperature_c: float, relative_humidity_pct: float, rain_24h_mm: float, day_length: float, constants: Constants = '1987') -> float` Eqs. 11-17. Moisture of loosely compacted organic layers. `constants="cffdrs"` writes Eq. 12 as the program does, `280 / exp(0.023 P)`, for the report's `exp(5.6348 - P / 43.43)`. ### `drought_code(previous: float, *, temperature_c: float, rain_24h_mm: float, day_length: float) -> float` Eqs. 18-23. Deep, compact organic layers — the seasonal drought memory. ### `initial_spread_index(ffmc: float, *, wind_speed_kmh: float, constants: Constants = '1987') -> float` Eqs. 24-26. Expected rate of spread — where wind enters the chain. The FFMC goes back to moisture on the scale of `constants`, as in `fine_fuel_moisture_code`. ### `buildup_index(dmc: float, dc: float) -> float` Eqs. 27-28. Total fuel available to the fire. ### `fire_weather_index(isi: float, bui: float) -> float` Eqs. 29-31. The published index: intensity of a spreading fire. ### `advance(state: FwiState, *, month: int, temperature_c: float, relative_humidity_pct: float, wind_speed_kmh: float, rain_24h_mm: float, params: FwiParams) -> FwiOutputs` One day of the chain: yesterday's codes plus today's noon reading. ## `fwi_chain.walk` Walking the chain over many days, and re-walking it when better rain arrives. `fwi_chain.advance` is one day. A service that keeps a chain alive has to do three more things, and they are the same wherever the weather comes from and wherever the state is stored: * resume from the last stored day, across days with no observation, without welding the chain over a gap too long to mean anything (`walk_chain`, `days_to_walk`); * compute a forecast day without ever storing it (`writable_days`); * redo the last days when a better rain measurement turns up, keeping the temperature, humidity and wind already used (`rewalk_with_rain`, `correct_rain`). Everything here is a pure function of its arguments. Days are `datetime.date` values the caller supplies: nothing reads a clock, so "today" is always an argument. Reading and writing the state, and fetching the weather or the rain, stay with the caller. ### `class NoonObservation(temperature_c: float, relative_humidity_pct: float, wind_speed_kmh: float, rain_24h_mm: float)` The four daily inputs of the chain, read at local noon. ### `class ChainPoint(day: date, state: FwiState, chain_days: int)` A chain as of one day: where a walk resumes from. `chain_days` counts the days the chain has actually been advanced since it last started from the standard codes. It is what tells a settled drought code from one still reporting its seed. ### `class ChainDay(day: date, outputs: FwiOutputs, chain_days: int, observation: NoonObservation)` One walked day: the outputs, and the observation that produced them. #### `ChainDay.point: ChainPoint` This day as the starting point of the next walk. ### `walk_chain(observations: Mapping[date, NoonObservation], days: Sequence[date], *, start: ChainPoint | None, params: FwiParams, max_gap_days: int) -> list[ChainDay]` Walk one chain over `days`, from `start` or from the standard codes. `start` is the most recent stored point strictly before `days[0]`, or `None` when there is none. A day with no observation is **skipped, not zeroed**: inventing a reading would inject a fake drying day that the recursion would carry for weeks. A `start` more than `max_gap_days` before `days[0]` is discarded and the walk restarts from `params.initial_state` with `chain_days` back at zero. Carrying a drought code across weeks of missing weather as if the days were consecutive produces a number with no history behind it. Days missing *inside* the window are not counted against `max_gap_days`: only the distance from `start` is. ### `days_to_walk(target: date, *, last_day: date | None, max_gap_days: int) -> list[date]` The days to walk to bring a chain up to `target`, earliest first. From the day after `last_day` (the last stored day before `target`), so a jump two days ahead does not skip the drying in between, but never further back than `max_gap_days` before `target`. With no stored day the answer is `target` alone. Empty when `last_day` is not before `target`. ### `start_is_stale(start: ChainPoint, day: date, *, max_gap_days: int) -> bool` Whether `start` is too old to carry a chain to `day`. True when `start` is more than `max_gap_days` before `day`. It is the test `walk_chain` applies to `days[0]`; ask it of the day you are walking **to** when the walk does not begin right after `start`. ### `catch_up(observations: Mapping[date, NoonObservation], target: date, *, start: ChainPoint | None, params: FwiParams, max_gap_days: int) -> list[ChainDay]` Bring one chain up to `target`: the daily update, in one call. A `start` more than `max_gap_days` before `target` is discarded, at exactly that limit, and `target` alone is walked from the standard codes. Otherwise every day after `start` up to `target` is walked, so no drying day in between is skipped. This is `start_is_stale`, `days_to_walk` and `walk_chain` in the order that keeps a stale state from being carried: calling `days_to_walk` first trims the window to `max_gap_days`, and `walk_chain` then measures the gap from the trimmed window, so a state up to twice the limit old would pass. ### `writable_days(walked: Iterable[ChainDay], *, today: date) -> list[ChainDay]` The walked days that may be stored: `today` and before. A forecast day is worth computing and must never be written. A stored forecast would become tomorrow's predecessor, and the operational chain would end up recursing on a prediction. ### `rewalk_with_rain(rows: Sequence[ChainDay], start: ChainPoint, rain: Mapping[date, float | None], *, params: FwiParams, max_gap_days: int) -> list[ChainDay]` Redo `rows` from `start` with the rain given, in millimetres. Each row keeps its temperature, humidity and wind. Its rain becomes `rain[row.day]`; where that is missing or `None` the row's own rain stays, because a hole in the measurement is not a dry day. `rows` are in day order and all after `start.day`. The walk stops at the first row more than `max_gap_days` after the one before it: the original chain restarted from the standard codes there, and welding it would invent its history. `chain_days` continues from `start` rather than being copied from the old rows. ### `correct_rain(series: Sequence[ChainDay], *, since: date, rain: Mapping[date, float | None], params: FwiParams, max_gap_days: int, weather: Mapping[date, NoonObservation] | None = None) -> list[ChainDay]` Redo one chain's stored days from `since` on, with the rain given. `series` is the stored chain in day order, reaching back before `since`. The walk restarts from the last row before `since`; a chain born later restarts from its own first row, which is left as it is. Every row after that one is redone with `rewalk_with_rain` and returned, so the days that follow the corrected ones move with them. With `weather`, a row whose day is in it takes that observation in place of its stored one before the rain is applied: analysed noon weather replacing the forecast the row was first written with. Idempotent: the same series corrected twice with the same rain gives the same rows. ## `fwi_chain.noon` The noon reading of a day, from hourly weather. The chain wants one reading a day, taken at local solar noon: temperature, humidity and wind of that hour, and the rain of the 24 hours before it. Weather usually comes hour by hour. Two things can go wrong on the way, and both are silent unless someone counts: * the noon hour is missing, and the nearest hour that has the three values is taken instead. An hour or two away is still a noon reading; nine hours away is the weather of the night; * hours of rain are missing, and a sum over what is there reads them as dry. A storm in the missing hours becomes a dry day, and the drought codes carry it for weeks. `noon_reading` takes the largest distance from noon and the fewest hours of rain it may accept as arguments, with no defaults, and always says which hour it read and how many hours of rain were not measured. Pure: the samples are the caller's, and so is the time zone. `noon_hour` is an hour on the samples' own clock (for samples in UTC over Italy, 11). ### `class HourlySample(time: datetime, temperature_c: float | None = None, relative_humidity_pct: float | None = None, wind_speed_kmh: float | None = None, rain_mm: float | None = None)` One hour of weather. `None` is "not measured", never zero. `rain_mm` is the rain of the hour that ends at `time`. A dry hour is `0.0`; an hour nobody measured is `None`. #### `HourlySample.has_fire_weather: bool` Whether temperature, humidity and wind are all there. ### `class NoonReading(day: date, observation: NoonObservation | None, refused: Refusal | None = None, time: datetime | None = None, hours_from_noon: int | None = None, rain_hours: int = 0, rain_hours_missing: int = 24, rain_measured_mm: float = 0.0)` What was read for one day, and how good a reading it is. `observation` is `None` when the day has no usable reading, and `refused` says why. The other fields are filled whenever an hour with the three values was found, also when the reading was then refused. ### `noon_reading(samples: Iterable[HourlySample], day: date, *, noon_hour: int, max_hours_from_noon: int | None, min_rain_hours: int) -> NoonReading` The noon reading of `day` from hourly `samples`. The hour read is the one of `day` nearest to `noon_hour` among those that have temperature, humidity and wind (the earlier one on a tie). The rain is the sum of the hours after `time - 24 h` up to `time`: the window moves with the hour read. `max_hours_from_noon`: the reading is refused when the hour read is further than this from `noon_hour`; `None` accepts any hour of the day. `min_rain_hours`: the reading is refused when fewer than this many of the 24 hours of rain were measured; `0` accepts any, and then missing hours count as dry. Both are required: how much to accept is a choice, and a default would make it for the caller. Humidity is kept within 0-100 and wind and rain at 0 or above, as the chain itself does. Samples are expected one per hour. ### `noon_readings(samples: Iterable[HourlySample], days: Sequence[date], *, noon_hour: int, max_hours_from_noon: int | None, min_rain_hours: int) -> dict[date, NoonReading]` `noon_reading` for each of `days`, reading the samples once. The same answers as calling it day by day. Each day looks only at its own samples and at those of the day before, so a year of hours costs a year of hours and not a year for every day. The observations the chain takes are `{d: r.observation for d, r in readings.items() if r.observation}`. ## `fwi_chain.climatology` Where an FWI falls in the distribution of its place and its month. An FWI of 30 is an ordinary August day in one place and a once-in-a-decade day in another. A climatology says which: years of chain summarised, per place and per month, in 21 quantiles (0, 5, ..., 100). Pure statistics on lists of numbers. Where the years of weather come from and where the quantiles are stored stay with the caller. ### `QUANTILE_LEVELS: tuple[float, ...]` The levels of the stored quantiles: 0, 5, ..., 100. ### `quantiles(values: Sequence[float]) -> list[float]` The 21 quantiles of `values`, linearly interpolated between ranks. Raises `ValueError` on an empty sequence. ### `percentile(value: float, q: Sequence[float]) -> float` The percentile (0-100) at which `value` falls among the quantiles `q`. Interpolated between the two quantiles around it; outside the distribution it is 0 or 100. On a flat stretch (many winter days at FWI 0) it takes the centre of the stretch, so a value equal to half the distribution reads as neither its minimum nor its maximum. Raises `ValueError` unless `q` has one value per `QUANTILE_LEVELS` entry. ### `node_ceiling(per_month: Mapping[int, Sequence[float]], *, quantile: float, months: Iterable[int], minimum: float, maximum: float) -> float | None` The FWI that counts as "full" in one place, from its climatology. The mean, over `months`, of the monthly quantile at level `quantile`, kept between `minimum` and `maximum`. `per_month` maps a month (1-12) to its 21 quantiles; months missing from it, or without all 21, are left out. `None` when none of `months` has a climatology. Raises `ValueError` when `quantile` is not one of `QUANTILE_LEVELS`. ### `accumulate_monthly(observations: Mapping[date, NoonObservation], days: Sequence[date], per_month: MutableMapping[int, list[float]], *, state: FwiState, days_walked: int, params: FwiParams, spinup_days: int) -> tuple[FwiState, int]` Advance the chain over `days` and file each day's FWI under its month. Returns the new state and the new count of days walked, to pass back in for the next stretch (a year at a time, typically). The FWI values are **appended to** `per_month[month]`, which the caller owns: a missing month is created. A day with no observation is skipped, not zeroed. The first `spinup_days` walked days move the chain but stay out of the distribution: the chain starts from the standard codes and the drought code takes weeks to forget them. ### `coverage_is_valid(observed: Iterable[date], days: Sequence[date], *, max_gap_days: int, min_fraction: float = 0.95) -> bool` Whether a stretch of days has enough observations to enter a climatology. `days` is the full stretch in order (a year, typically) and `observed` the days in it that have an observation. Valid when at least `min_fraction` of the days are observed and no run of missing days, including at either end, is longer than `max_gap_days`. A chain walked across a longer hole would treat its two sides as consecutive days. ## `fwi_chain.danger` The fire danger class of an FWI, as EFFIS maps it. The European Forest Fire Information System colours its fire danger maps in six classes, the same for every country. The boundaries are the ones EFFIS publishes in its technical background, "Fire danger forecast" (https://forest-fire.emergency.copernicus.eu/about-effis/technical-background/fire-danger-forecast, read on 2026-11-28); "very extreme" was added in June 2021. A class is a convention about a number, not a measurement: the same FWI is an ordinary summer day in one place and a rare one in another. For that, see `fwi_chain.climatology`. ### `EFFIS_FWI_CLASSES: tuple[tuple[float, str], ...]` Each class with the FWI it starts at, lowest first. ### `effis_class(fwi: float) -> str` The EFFIS fire danger class of `fwi`. A boundary belongs to the class above it: 11.2 is "moderate". EFFIS writes the classes as ranges ("11.2 - 21.3") and does not say which side a boundary falls on; the last one it writes as "> 70". Raises `ValueError` for a negative or non-finite FWI. ## `fwi_chain.explain` What moved the index from one day to the next. The FWI of today differs from yesterday's for two reasons. The chain has a memory: with the very same weather the codes would still have moved, because fuel that is drying keeps drying. And the weather changed. This module separates the two, and splits the second among the four readings. The readings act together (wind matters more on dry fuel), so "the effect of the rain" depends on what else is taken to have changed. The split used here is the Shapley value: the effect of a reading is its average effect over every order in which the four could have changed from yesterday's values to today's. It is the one split in which the four effects add up exactly to the weather's share, and none depends on the order the readings are listed in. It is arithmetic on the chain: the same equations, run 16 times. It says what moved the number, not why the weather changed. ### `INPUTS: dict[Input, str]` The four readings, and the field of `NoonObservation` each one is. ### `class Driver(input: Input, yesterday: float, today: float, effect: float)` One reading, and what its change did to today's FWI. ### `class Explanation(fwi_yesterday: float, fwi_today: float, change: float, carry_over: float, weather: float, drivers: tuple[Driver, ...])` Today's FWI against yesterday's, taken apart. `change == carry_over + weather` and `weather == sum(d.effect for d in drivers)`, to floating-point rounding. ### `explain_change(previous: ChainDay, today: ChainDay, *, params: FwiParams) -> Explanation` What moved the FWI from `previous` to `today`. `previous` and `today` are two walked days, `today` computed from the state `previous` left (consecutive rows of `walk_chain`). `params` are the ones the chain was walked with. ## `fwi_chain.facts` The chain's answers as data: what a tool, a report or a model can quote. Every function returns a plain `dict` (JSON-ready) with the numbers, their units in the key names (`_c`, `_pct`, `_kmh`, `_mm`, `_days`; the six codes have no unit), and the rule that goes with every answer: A fire weather index is not an alert. A language model may word these facts; it never computes them. The numbers come from here, and `fwi_chain.check.check_text` checks a text against them. Codes and effects are rounded to one decimal, as fire services publish them; the chain itself keeps every digit. ### `day_facts(day: ChainDay, *, previous: ChainDay | None = None, params: FwiParams | None = None, month_quantiles: Sequence[float] | None = None, spinup_days: int | None = None) -> dict[str, Any]` One walked day: the readings, the six codes, the class, and what moved it. With `previous` (the walked day before) and `params`, `change` says what moved the FWI: the chain's memory, and each of the four readings (`fwi_chain.explain.explain_change`). With `month_quantiles` (the 21 quantiles of this place and month), `climatology` says where the FWI falls among them. With `spinup_days`, `settled` is false while the chain has walked fewer days than that and is still reporting its seed. With `params`, `constants` names the printing the codes were computed with: `"1987"` (the report) or `"cffdrs"` (the 1985 program). ### `walk_facts(walked: Sequence[ChainDay], *, params: FwiParams, quantiles_by_month: Mapping[int, Sequence[float]] | None = None, spinup_days: int | None = None) -> dict[str, Any]` A walked stretch of days: each day, the peak, the rain, and the last day in full. `series` has one row per walked day. `last` is `day_facts` of the last day, with what moved it when there is a day before. `constants` names the printing of the constants the chain was walked with. Raises `ValueError` on an empty walk: no day was walked, and "no fire danger" would be a different statement. ### `distribution_facts(values: Sequence[float], *, value: float | None = None) -> dict[str, Any]` A list of FWI values as 21 quantiles, and where `value` falls among them. ## `fwi_chain.check` Check that a text quotes the facts: no number invented, none in the wrong unit. A model turns the facts of `fwi_chain.facts` into words. The faults that matter here are three: * **invented**: a number that is in no fact; * **unit**: a number that is a fact, but of another unit. The classic one: the 12.4 mm of rain written as 12.4 %, or a wind in km/h given as a temperature. The six codes have no unit: "an FWI of 23.4 %" is a fault; * **rounded**: a number close to a fact, but not the fact rounded to the decimals written (`23.5` for 23.4). A number may be written with fewer decimals than the fact (`23` for 23.4) or, from 100, as a round number (`500` for 512). Dates, years and clock times (`10/10`, `10 October 2026`, `2026-10-10`, `12:00`) are not checked, nor numbers that are in the question. The check knows that a number is a fact of the right unit, not that it is said of the right thing: "the DC is 23.4" passes when 23.4 is the FWI. And the more numbers the facts hold, the more a small invented one can pass by chance: against a whole series of days, "12 storms" passes if any reading is 12. Check a text against the facts of the day it is about, not against the whole walk. ### `class Misquote(text: str, unit: str | None, fault: Fault, nearest: str | None = None)` A number of the text that is not a fact as written. ### `facts_of(facts: Any, path: str = '') -> Iterator[tuple[str, float, str | None]]` Every number in `facts`, with its path and the unit its key names. ### `parse_number(token: str) -> tuple[float, int]` A number as written -> its value and its decimals. `1,603` is 1603; `2,5` is 2.5. ### `check_text(text: str, facts: Any, *, question: str = '') -> list[Misquote]` The numbers of `text` that are not facts of their unit. Empty: faithful. ## `fwi_chain.mcp_server` The MCP server: the chain as tools an assistant can call. pip install "fwi-chain[mcp]" fwi-chain-mcp # on standard input and output fwi-chain-mcp --http 8772 # streamable HTTP, at http://127.0.0.1:8772/mcp The tools compute only from what the call gives them: no network, no weather of their own, no clock. Bring the noon readings from a station or a model; the answer is the chain's, with the rule that a fire weather index is not an alert. The tools are the functions of `fwi_chain.facts`, and `check` is `fwi_chain.check.check_text`. This module is the only one that needs the `mcp` extra. Nothing else in the package imports it. ### `create_server(**options: Any = {}) -> MCPServer[Any]` The MCP server with its four tools. `options` go to `MCPServer`. ### `run(*, http_port: int | None = None, http_host: str = '127.0.0.1') -> None` Serve on standard input and output, or over streamable HTTP at `/mcp`. ### `main(argv: Sequence[str] | None = None) -> None` Entry point of `fwi-chain-mcp`. # Validation The FWI equations are a **standard**, not a design choice. The only way to know they were transcribed correctly is to compare them with a known, published case. A test suite of properties alone ("FWI goes up with wind") would stay green with a wrong coefficient. That is why the suite has two layers. ## 1. Against cffdrs, over 48 days [`cffdrs`](https://cran.r-project.org/package=cffdrs) is the reference R implementation. It ships a test series of 48 days (13 April to 30 May 1985, the sample data of Van Wagner & Pickett 1985) and its own output for it. The [benchmark](benchmark.md) walks this library over the same days, in CI: | Code | Largest difference from cffdrs over 48 days | |---|---| | FFMC | 0.123 | | DMC | 0.065 | | DC | 0.005 | | ISI | 0.252 | | BUI | 0.063 | | FWI | 0.254 | On all 48 days the two give the same EFFIS danger class. The numbers are close, not equal, and the reason is known. This library follows the equations as printed in Van Wagner (1987): 147.2 in the FFMC scale (Eq. 1), 1/43.43 in the DMC (Eq. 12). cffdrs follows the FORTRAN program of 1985, which has 147.27723 and 0.023. With those two constants all six codes agree with cffdrs to 0.006: since 1.4.0 they are an option, `FwiParams.constants="cffdrs"` or `CFFDRS_PARAMS`, measured in the benchmark next to the default. The default stays the report, so no stored chain moves. The two files of the cffdrs series are not in this repository (cffdrs is GPL-2): the benchmark downloads them at a fixed commit and checks their SHA-256. See [the benchmark](benchmark.md). !!! note "A correction" Up to 1.1.0 these pages said the library was "verified against the cffdrs reference day to 1e-9". That was not accurate. The inputs of that day are the first day of the cffdrs series; the six expected values to 1e-9 are this library's own. cffdrs gives FFMC 87.65, ISI 10.78 and FWI 10.04 for that day, against 87.69, 10.85 and 10.10 here. ## 1b. The first day, to 1e-9 [`tests/test_chain.py::test_published_reference_day`](https://github.com/agent-engineering-studio/fwi-chain/blob/main/tests/test_chain.py) pins the six codes of the first day of that series, as this library computes them: | Input | Value | |---|---| | Start state | FFMC 85, DMC 6, DC 15 (the standard start-up codes) | | Month | April | | Temperature | 17.0 °C | | Relative humidity | 42 % | | Wind | 25 km/h | | Rain | 0 mm | | Output | Pinned value | Tolerance | |---|---|---| | FFMC | 87.692980092774 | 1e-9 absolute | | DMC | 8.5450511359998 | 1e-9 | | DC | 19.013999999999996 | 1e-9 | | ISI | 10.853661073312 | 1e-9 | | BUI | 8.4904265358371 | 1e-9 | | FWI | 10.096371392382 | 1e-9 | A pinned value shows a change; it does not show the value is right. What shows that is the comparison above, and the DC, which can be checked by hand: see [the worked example](how-fwi-works.md#a-worked-example-by-hand). ```bash python examples/01_single_day.py ``` ## 2. What a single day cannot reach The cffdrs series has 14 days with rain, so it reaches the rain branches. The rest of the suite covers each of them on purpose, along with the behaviour the science requires: | Test | What it guards | |---|---| | `test_light_rain_is_intercepted_by_the_canopy` | rain below 0.5 / 1.5 / 2.8 mm does not wet the fuel | | `test_heavy_rain_lowers_every_code` | heavy rain wets all three codes, not just FFMC | | `test_dmc_wetting_covers_the_three_slopes_of_eq_13` | every branch of Eq. 13 (DMC ≤ 33, ≤ 65, > 65) | | `test_the_saturation_correction_reads_the_pre_rain_moisture` | Eq. 3a applies only to fuel already saturated before the rain | | `test_codes_stay_inside_their_domains` | no NaN or negative values under extreme sirocco, frost, or a 200 mm cloudburst | | `test_buildup_index_survives_both_codes_at_zero` | Eq. 27's division by zero on a soaked landscape | | `test_the_drought_code_remembers_far_longer_than_the_fine_fuel` | the memory asymmetry: after a storm and a dry week FFMC fully recovers, DC recovers less than half | | `test_fwi_is_monotone_in_both_of_its_inputs` | more spread or more fuel never lowers the index | | `test_a_day_length_table_of_the_wrong_size_is_refused` | an 11-month table cannot silently shift the year | | `tests/test_examples.py` | every script in `examples/` runs | ## 3. The quality gate Every push and pull request runs, on Python 3.12 and 3.13: ```bash uv run ruff check # lint uv run ruff format --check # formatting uv run mypy # --strict, on src and tests uv run pytest --cov # tests, coverage must stay ≥ 90 % uv run python -m benchmarks.run --check # the known cases uv run python -m benchmarks.faithful --check # the text check uv build # the package builds ``` Locally, `make check` runs the same gate. ## Found a disagreement? If `fwi-chain` disagrees with another implementation (cffdrs, xclim, a national service's published values), please [open an issue](https://github.com/agent-engineering-studio/fwi-chain/issues/new/choose) with the inputs, the start state, and both outputs. New reference vectors are among the most valuable contributions to this project. # Benchmark: known cases A small, fixed set of cases where the answer is known before the code runs. The equations of the FWI are a standard: the only way to know they were transcribed right is to compare them with somebody else's numbers. ```bash uv run python -m benchmarks.run # the table uv run python -m benchmarks.run --check # CI: fails if an outcome or a measure changed uv run python -m benchmarks.run --write # accept the new results (results.json) uv run python -m benchmarks.faithful --check # the text check finds the faults it should ``` The cffdrs series is downloaded the first time (about 6 KB, checked by SHA-256; see [`cffdrs/README.md`](cffdrs/README.md)). With no network those cases print **SKIPPED, not passed**; CI adds `--require-download`, which makes a skip a failure. > **A fire weather index is not an alert.** A case here says whether the chain > computes what it should, nothing about fires. ## The cases | Case | Where the answer comes from | What is checked | |---|---|---| | **48 days of cffdrs** | the test series of the `cffdrs` R package, 13 April to 30 May 1985, and cffdrs's own output for it | each of the six codes within a stated distance of cffdrs, every day; the same EFFIS class, every day | | **48 days of cffdrs, `constants="cffdrs"`** | the same | each code within 0.007 of cffdrs (measured: 0.006 at most); the same class, every day | | **The first day, by hand** | Van Wagner (1987) Eq. 22-23, on paper: DC = 15 + (0.36 * 19.8 + 0.9) / 2 = 19.014 | to 1e-9 | | **The first day, pinned** | this library's own six codes | to 1e-9, so that a change is seen. They prove nothing by themselves | | **The rain each code ignores** | Van Wagner (1987) Eq. 2, 11, 18: 0.5, 1.5 and 2.8 mm | rain at the limit leaves the code as a dry day; a tenth above lowers it | | **A stored state too old** | the rule of Limen's backfill | `catch_up()` carries a state exactly at the limit, and discards it one day past | ## What the 48 days say This library and cffdrs do not give the same numbers, and the benchmark keeps the difference in view instead of hiding it behind a loose tolerance. | Code | Largest difference over 48 days: `"1987"` (default) | `"cffdrs"` | |---|---|---| | FFMC | 0.123 | 0.005 | | DMC | 0.065 | 0.006 | | DC | 0.005 | 0.005 | | ISI | 0.252 | 0.005 | | BUI | 0.063 | 0.006 | | FWI | 0.254 | 0.005 | The largest FWI difference is on 7 May 1985: 52.56 here, 52.31 in cffdrs, half a percent. **On all 48 days the two give the same EFFIS class.** The cause is known. The 1987 report prints the FFMC scale with the constant 147.2 (Eq. 1); the FORTRAN program of Van Wagner & Pickett (1985), which cffdrs follows, uses 147.27723. The DMC difference is of the same kind: Eq. 12 has 1/43.43 where the program has 0.023 (written `280 / exp(0.023 P)`). With those two constants changed, all six codes agree with cffdrs to 0.006, the digits cffdrs prints. The DC, which has no such constant, already agrees to 0.005. So: this library follows the report as printed, cffdrs the program. Neither is wrong; they are two printings of one standard, a quarter of an FWI point apart at most on this series. If you need cffdrs's digits, walk with `CFFDRS_PARAMS` (or `FwiParams(..., constants="cffdrs")`), from 1.4.0. The default does not change, so no stored chain moves. What the benchmark does **not** cover: no observed fire, no comparison with the FWI that EFFIS or a weather service publishes for a real place (that needs their weather, and belongs to whoever joins the two), no latitude other than the standard tables, no winter. ## The faithfulness set `faithful.json` has four questions about the 48 days, each with an answer written by hand that quotes the facts right and one with known faults: a number of another unit, one rounded wrong, one invented. `--check` fails when `fwi_chain.check.check_text` does not find exactly those faults. It tests the checker, not a model: no model's answers are in the set yet. Writing the set found two limits of the check, now in its documentation: a number that exists as a fact of another unit is reported as a unit fault even when it was simply made up ("2 days" against an effect of -2.0), and against a whole series of days a small invented integer can pass by chance. ## Data `cffdrs/`: see [its README](cffdrs/README.md) for the source, the checksums and the licence. The files themselves are downloaded, not kept here: cffdrs is GPL-2. # Riuso nella Pubblica Amministrazione fwi-chain calcola l'indice meteorologico di pericolo d'incendio (Fire Weather Index, Van Wagner 1987). Questa pagina è per un ente che vuole usarla: che cosa trova pronto, che cosa resta a lui. !!! warning "Un indice di pericolo non è un'allerta" Dice quanto facilmente un incendio partirebbe e si propagherebbe con quel meteo, non che un incendio ci sarà. Il pericolo ufficiale in Europa è pubblicato da [EFFIS](https://forest-fire.emergency.copernicus.eu/); in Italia il bollettino di previsione incendi è del Dipartimento della Protezione Civile e delle Regioni. ## Il diario del pericolo d'incendio Una pagina pronta, in italiano, con [Bootstrap Italia](https://italia.github.io/bootstrap-italia/) servito dalla pagina stessa, senza CDN: - l'ente incolla o carica il meteo di mezzogiorno di una località, un giorno per riga: temperatura, umidità, vento, pioggia delle 24 ore; - la pagina mostra la catena giorno per giorno: i sei codici, la classe di pericolo EFFIS, il grafico; - scelto un giorno, dice **che cosa ha mosso l'indice**: la memoria della catena e i punti spostati da vento, umidità, temperatura e pioggia; - segna i giorni in cui la catena è ancora in avviamento; - esporta la tabella in CSV. ![Il diario: la catena giorno per giorno](images/diario-catena.png) ![Che cosa ha mosso l'indice il 15 luglio 2025](images/diario-che-cosa-ha-mosso.png) Nelle immagini c'è l'esempio incluso: Gioia del Colle (BA), dal 1 maggio al 30 settembre 2025, meteo ricostruito dalla rianalisi ERA5 e distribuito da [Open-Meteo](https://open-meteo.com/) con licenza CC BY 4.0. È un modello, non una stazione: serve a vedere la pagina, non a dire com'è andata quell'estate. ```bash FWI_CHAIN_ENTE="Comune di Gioia del Colle" docker compose up ui # http://localhost:3007 ``` Le istruzioni sono in [`app/README.md`](https://github.com/agent-engineering-studio/fwi-chain/tree/main/app). ## Che cosa non fa - **Non scarica il meteo.** Lo porta l'ente: dalla sua stazione, o da una fonte aperta (qui sotto). - **Non mostra incendi, perimetri o previsioni.** Il monitoraggio è un altro progetto, [Limen](https://github.com/agent-engineering-studio/limen). - **Non dice dove partirà un incendio.** Combustibile, pendenza e innesco contano quanto il meteo, e l'indice non li vede. - **Non è il bollettino.** La classe è quella di EFFIS applicata al numero calcolato qui, non il livello di pericolosità che l'autorità pubblica. ## Da dove prendere il meteo La catena chiede quattro numeri al giorno, letti a mezzogiorno solare. Fonti aperte che li danno: - **la stazione dell'ente** o della rete regionale (ARPA, centro funzionale): la più vicina alla realtà del posto; - **[Open-Meteo](https://open-meteo.com/)**: un'API senza chiave, gratuita per uso non commerciale fino a 10.000 chiamate al giorno, con il meteo ora per ora dal 1940 (la rianalisi ERA5 di Copernicus) e le previsioni; - **ERA5 / ERA5-Land** dal Climate Data Store di Copernicus, per chi lavora su griglia. Chi ha il meteo ora per ora ricava la lettura di mezzogiorno con `noon_readings`, che rifiuta una lettura presa lontano da mezzogiorno o con ore di pioggia mancanti, e dice quali. Un giorno che manca si lascia vuoto: non si scrive mai 0. Una pioggia a zero è un giorno asciutto, non un giorno senza dato. ## Che cosa resta all'ente - **Il meteo e la sua qualità.** Un modello a 9 km non vede un temporale: la catena con la pioggia sbagliata resta all'estate. - **L'avviamento.** Partendo dai valori standard servono settimane di meteo prima che i codici di siccità dicano qualcosa. La pagina lo segnala. - **La latitudine.** Le tabelle della durata del giorno sono quelle di Van Wagner per 46°N: vanno bene per l'Italia, non ovunque. - **La decisione.** Che cosa fare con un indice alto è una scelta dell'ente e dell'autorità competente: la pagina dà i numeri, non la scelta. - **La pubblicazione.** La pagina ascolta solo su `127.0.0.1`: per metterla sul sito va dietro il proxy dell'ente. ## Quanto fidarsi La libreria è confrontata a ogni modifica con i 48 giorni della serie di prova di `cffdrs`, l'implementazione di riferimento in R: al massimo 0,25 punti di FWI di differenza, la stessa classe tutti i 48 giorni. La differenza ha una causa nota: due costanti stampate in modo diverso nel 1985 e nel 1987. Con `CFFDRS_PARAMS`, le costanti del 1985, la differenza scende a 0,006. I dettagli sono nel [benchmark](benchmark.md). ## Per chi sviluppa Il software è descritto in [`publiccode.yml`](https://github.com/agent-engineering-studio/fwi-chain/blob/main/publiccode.yml), con licenza Apache-2.0. Non usa dati personali e non richiede chiavi o account. # Social media kit Everything you need to share `fwi-chain`: images, ready-to-post texts, and hashtags. Copy, adapt, and post. Thank you! **Link:** https://github.com/agent-engineering-studio/fwi-chain **Install:** `pip install fwi-chain` ## Images | Image | Use it for | File | |---|---|---| | Social card, 1280 × 640 | GitHub social preview, link previews, X / LinkedIn / Mastodon | [`images/social-preview.png`](images/social-preview.png) | | The chain diagram | explaining what the FWI is | [`images/fwi-chain-diagram.svg`](images/fwi-chain-diagram.svg) | | A fire season | the "wow" chart | [`images/fire-season.svg`](images/fire-season.svg) | | Three memories | the science hook | [`images/moisture-codes.svg`](images/moisture-codes.svg) | | Storm recovery | the "did you know" hook | [`images/memory.svg`](images/memory.svg) | | Cold restart | the engineering hook | [`images/restart.svg`](images/restart.svg) | > Most platforms do not accept SVG uploads. Export a PNG by opening the SVG in a > browser and taking a screenshot, or run > `uv run --with cairosvg python -c "import cairosvg; cairosvg.svg2png(url='docs/images/fire-season.svg', write_to='fire-season.png', output_width=2000)"`. **Set the GitHub social preview once:** repository → *Settings* → *General* → *Social preview* → upload `docs/images/social-preview.png`. ## LinkedIn > 🔥 **Wildfire danger, in about 300 lines of pure Python.** > > We just open-sourced **fwi-chain**: the Canadian Forest Fire Weather Index (FWI), the index fire services and the European EFFIS publish every day, as small, typed, dependency-free Python functions. > > Four noon readings (temperature, humidity, wind, rain) → six numbers that say how easily a fire would start, how fast it would spread, and how hard it would be to fight. > > What makes it different: > ✅ Zero dependencies: it fits in a database job, a stream processor, a serverless function > ✅ Measured, not just tested: 48 days against cffdrs in CI, at most 0.25 FWI points apart > ✅ The "memory" of the forest floor (weeks of drought) is an explicit state you persist, not hidden in an array > ✅ Every line tied to an equation number in Van Wagner (1987) > > It already runs the wildfire danger chain for every ~9 km weather node in Italy. > > We're looking for contributors: fire scientists, meteorologists, Python developers, technical writers. There are good first issues for everyone. > > 👉 https://github.com/agent-engineering-studio/fwi-chain > > #wildfire #opensource #python #climate #firescience #meteorology #EFFIS *(attach `social-preview.png` or `fire-season.png`)* ## X / Bluesky / Mastodon **Launch (≤ 280 chars)** > 🔥 fwi-chain: the Canadian Fire Weather Index in pure Python. > Zero deps · fully typed · measured against the cffdrs test series · Apache-2.0 > > pip install fwi-chain > https://github.com/agent-engineering-studio/fwi-chain > #Python #wildfire #opensource **Science hook** (attach `memory.svg` as PNG) > After a 40 mm storm in July: > 🌾 fine fuels are bone-dry again in 2 days > 🍂 the duff layer takes a week > 🪵 deep drought takes 17+ days > > That memory is why fire danger is a *chain*, not a formula. Explained, with code: https://github.com/agent-engineering-studio/fwi-chain/blob/main/docs/how-fwi-works.md **Engineering hook** (attach `restart.svg` as PNG) > Bug you won't see in a unit test: restart your fire-danger model mid-season from default values and it underestimates danger for weeks. > > fwi-chain makes the state explicit, so you can't forget to persist it. 🧵👇 > https://github.com/agent-engineering-studio/fwi-chain **Thread (5 posts)** 1. 🔥 How do fire services decide that today is "extreme" fire danger? Most use the Canadian Fire Weather Index. We open-sourced a tiny, verified Python implementation. A thread on how it works 🧵 2. It needs only 4 noon readings: temperature, humidity, wind, and 24 h rain. From them it computes 3 moisture codes, one for each layer of the forest floor, from surface litter to deep soil. *(diagram)* 3. Each layer has a different memory: ~16 hours, ~12 days, ~52 days. So today's danger depends on the whole season, and that's why it's a *chain*. *(moisture-codes)* 4. Forget that memory (restart mid-season) and you underestimate danger for weeks. fwi-chain hands you the state as a plain value: store it in SQL, a file, a cache. *(restart)* 5. Zero deps, mypy --strict, measured against cffdrs in CI, Apache-2.0. Contributors welcome: reference data, latitude tables, docs, translations. ⭐ https://github.com/agent-engineering-studio/fwi-chain ## Reddit (r/Python, r/datascience, r/gis, r/meteorology) **Title:** I open-sourced a zero-dependency, verified implementation of the Canadian Fire Weather Index **Body:** > The FWI is the fire danger index used across Canada, by EFFIS for Europe, and by many other agencies. I extracted the implementation we use in production (Italy, ~9 km grid) into a standalone package: > > - pure functions, no NumPy, no I/O, about 300 lines, `mypy --strict` > - measured against the 48-day cffdrs test series in CI (at most 0.25 FWI points apart, same class every day), plus tests for every rain branch and for physical bounds > - the recursive state (the "memory" of the forest floor) is an explicit dataclass you persist yourself > > For gridded climate data xclim is still the better tool. This one is for services, databases and streams. > > Docs explain the science in plain words, with charts generated by the library. Feedback and contributions very welcome! > > https://github.com/agent-engineering-studio/fwi-chain ## Hacker News **Title:** Show HN: fwi-chain – the Canadian Fire Weather Index in pure, verified Python ## Hashtags `#wildfire` `#firescience` `#FWI` `#Python` `#opensource` `#climate` `#meteorology` `#EFFIS` `#GIS` `#climatechange` `#forestfire` `#datascience` ## Suggested GitHub topics Add them under *About* → ⚙️ on the repository page: ``` fire-weather-index wildfire fwi python meteorology climate fire-danger forest-fire cffdrs van-wagner zero-dependency typed ``` ## Key facts (for writing your own post) - Implements Van Wagner (1987), *Forestry Technical Report 35*. - 6 outputs: FFMC, DMC, DC, ISI, BUI, FWI. - Python 3.12+, no runtime dependencies, Apache-2.0. - About 300 lines of library code. 48 days against cffdrs: at most 0.25 FWI points apart. - A few microseconds per location per day. - Extracted from Limen, which runs it on every ~9 km node in Italy. # Contributing to fwi-chain Thank you for considering a contribution! `fwi-chain` is small on purpose, which makes it a good place for a first open-source contribution, and a place where domain expertise in fire science or meteorology goes a long way. ## Ways to help (no code required) - ⭐ **Star the repo and share it.** The [social media kit](docs/social-kit.md) has ready-made posts and images. - 🐛 **Report a disagreement** with cffdrs, xclim, or a fire service's published values. - 📝 **Improve the docs.** If something confused you, it will confuse the next person too. - 🌍 **Tell us where you use it.** A short issue saying "we run this for region X" helps the project a lot. ## Good first issues These are well-scoped and don't require deep knowledge of the codebase. Please open an issue first to say you are taking one, so nobody duplicates the work. | Idea | Skills | Notes | |---|---|---| | More reference cases in `benchmarks/` | Python, a little R | another implementation's output, or a fire service's published values for known weather | | A table of day-length factors for other latitude bands | fire science | as ready-made `FwiParams` constants, with sources | | Daily Severity Rating (`dsr = 0.0272 * fwi ** 1.77`) | Python | a one-line function, plus a test and docs | | Comparison notebook against xclim | Python, xarray | in `docs/`, not a dependency | | Translations of `docs/how-fwi-works.md` | any language | Italian, Spanish, Portuguese, Greek and French are a good start for Mediterranean users | | Benchmarks | Python | `pytest-benchmark` or a small script in `docs/` | ## Larger ideas (discuss first) - **DC overwintering** (Turner & Lawson 1978; Lawson & Armitage 2008): carry the DC through a winter instead of restarting at 15. - **Hourly FFMC** (Van Wagner 1977), for sub-daily danger. - **Fire Behaviour Prediction (FBP) System** components, probably as a separate package. The guiding principle: **pure functions, no dependencies, every constant traced to a published equation.** ## Development setup (5 minutes) You need [uv](https://docs.astral.sh/uv/). ```bash git clone https://github.com/agent-engineering-studio/fwi-chain cd fwi-chain uv sync # creates .venv with the dev tools make check # lint + typecheck + tests: what CI runs ``` Other targets: ```bash make format # ruff format + autofix make test # pytest with coverage make figures # regenerate docs/images (needs network for matplotlib once) make build # build sdist + wheel ``` ## Project layout ``` fwi-chain/ ├── src/fwi_chain/ # no dependencies, no I/O, no clock │ ├── chain.py # Van Wagner's equations + advance() │ ├── walk.py # many days from a stored state, rain re-walk │ ├── noon.py # the noon reading from hourly weather │ ├── climatology.py # 21 quantiles, percentile, node ceiling │ ├── danger.py # the EFFIS classes │ ├── explain.py # what moved the index │ ├── facts.py, check.py # the answers as data, and the text check │ └── mcp_server.py # the MCP server: the only module behind an extra ├── tests/ # equations, parity with Limen, package promises, MCP ├── benchmarks/ # known cases (cffdrs series) and the faithfulness set ├── app/ # the page for a public body: its own package and lock ├── notebooks/ # written from examples/ by tools/make_notebooks.py ├── skills/, tools/ # the agent skill; llms.txt and notebook builders ├── examples/ # runnable, dependency-free scripts (01_… to 06_…) │ └── weather.py # deterministic synthetic season used by examples and figures ├── docs/ │ ├── *.md # guides, API reference, FAQ, social kit │ ├── images/ # figures (generated) and the chain diagram (hand-written SVG) │ └── scripts/make_figures.py └── .github/workflows/ # ci.yml (every push/PR), release.yml (tags → PyPI) ``` ## Rules of the road - **`make check` must pass**: ruff, `mypy --strict`, pytest (coverage ≥ 90 %) and the benchmark. `make help` lists every target. It is the same gate CI runs. - **Equations are transcribed, not tuned.** Any change to a constant in `chain.py` must cite the equation it comes from and come with a reference value that proves it. - **No runtime dependencies.** Tools used only for docs or development go in the `dev` group or run with `uv run --with`. - **Examples are documentation.** If you change the API, update `examples/` and `docs/` in the same PR. `tests/test_examples.py` will remind you. - **Commits** follow [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `docs:`, `test:`, `ci:`, …). - **Changelog**: add a line under `[Unreleased]` in `CHANGELOG.md` for user-visible changes. ## Pull request checklist - [ ] `make check` is green - [ ] tests cover the change (for equations: a reference value) - [ ] docs and examples updated if the API changed - [ ] `CHANGELOG.md` updated ## Releasing (maintainers) Bump `version` in `pyproject.toml`, move `[Unreleased]` to the new version in `CHANGELOG.md`, then push a tag `vX.Y.Z`. The release workflow checks that the tag matches the version, runs the tests, publishes to PyPI with trusted publishing, and creates a GitHub release. ## License Contributions are accepted under the project's license, Apache-2.0 (section 5 of the license: inbound = outbound). There is no separate CLA. --- name: fwi-chain description: Compute the Canadian Fire Weather Index (FFMC, DMC, DC, ISI, BUI, FWI; Van Wagner 1987) in Python with the fwi-chain library - one day from four noon readings, a chain walked over many days from a stored state, redone when better rain arrives, a climatology in 21 quantiles, the EFFIS danger classes, what moved the index from one day to the next, and a check that a text quotes the numbers right. Use when code or an answer needs a fire weather index, fire danger from weather, or mentions FWI, FFMC, DMC, DC, drought code, Van Wagner, cffdrs or fwi-chain. --- # fwi-chain `fwi-chain` answers one question: **how easily would a fire start and spread in this weather?** It has no dependencies. It fetches no weather: the caller brings one noon reading per day. It reads no clock: "today" is an argument. Full documentation: https://agentengineering.it/fwi-chain/ · everything as plain text: https://agentengineering.it/fwi-chain/llms-full.txt ## The rule that goes with every answer **A fire weather index is not an alert, and not a forecast of fires.** It says how easily a fire would start and spread, not that one will. The official fire danger for Europe is published by EFFIS (https://forest-fire.emergency.copernicus.eu/); in Italy the fire danger bulletin is issued by the Dipartimento della Protezione Civile and by the regions. For danger to people, point to the official bulletin and to 112. Never write "alert", "warning" or "a fire will start here" from an index alone. ## Setup ```bash pip install fwi-chain # the library, no dependencies pip install "fwi-chain[mcp]" # + the MCP server: fwi-chain-mcp ``` ## Recipe ```python from datetime import date from fwi_chain import STANDARD_PARAMS, ChainPoint, NoonObservation, catch_up, effis_class observations: dict[date, NoonObservation] = ... # one per day; a missing day is simply absent stored: ChainPoint | None = ... # the last point you saved, or None walked = catch_up( observations, date(2026, 7, 20), start=stored, params=STANDARD_PARAMS, max_gap_days=7 ) today = walked[-1] print(today.outputs.fwi, effis_class(today.outputs.fwi), today.chain_days) save(today.point) # the state is yours to persist ``` One day alone is `advance(state, month=..., temperature_c=..., ...)`. A whole window with a known start is `walk_chain`. Measured rain replacing a model's: `correct_rain`. Where a value falls in its place and month: `quantiles`, `percentile`. For an answer in words: `fwi_chain.facts` (`day_facts`, `walk_facts`, `distribution_facts`) gives the numbers as data, with what moved the index; before you send the text, `fwi_chain.check.check_text(text, facts)`. ## The traps - **The codes remember.** FFMC forgets in a day, DMC in about 12, DC in about 52. A chain started from the standard codes (85 / 6 / 15) says nothing about the drought until it has walked for weeks. Persist the state; do not restart each day. `chain_days` counts the days walked since the last start. - **Not measured is not dry.** A day with no reading is left out of `observations`, never given a rain of 0: an invented dry day is carried by the recursion for weeks. - **A stored state too old is not a state.** Past `max_gap_days` restart from the standard codes. Use `catch_up`: calling `days_to_walk` and then `walk_chain` yourself keeps a state up to twice the limit. - **Never store a forecast day.** Compute it, show it, and keep only `writable_days(walked, today=...)`: a stored forecast becomes tomorrow's predecessor. - **Noon, and the rain of the 24 hours before it.** Local solar noon readings; `rain_24h_mm` is the total up to that hour, not the calendar day's. From hourly weather use `noon_readings(samples, days, noon_hour=..., max_hours_from_noon=2, min_rain_hours=20)`: it refuses a reading taken far from noon or with hours of rain missing, and says which. Never sum the hours that happen to be there: a missing hour is not a dry hour. - **Units are in the names:** `temperature_c`, `relative_humidity_pct`, `wind_speed_kmh` (10 m wind, not m/s), `rain_24h_mm`. The six codes have no unit: never "an FWI of 30 %". - **The class is a convention, the percentile a fact about a place.** An FWI of 30 is an ordinary August day in Sicily and a rare one in the Alps. `effis_class` gives the first, `percentile` the second. - **What moved the index** (`explain_change`) is arithmetic on the chain: the chain's memory, and the FWI points moved by each reading. It does not say why the weather changed. Do not add causes that are not in it. - **Day-length tables are for 46°N.** Far from that latitude, or in the southern hemisphere, pass your own `FwiParams`. - **Not cffdrs's digits, unless asked.** The library follows Van Wagner (1987) as printed; cffdrs follows the 1985 FORTRAN program. Over cffdrs's 48-day test series they differ by at most 0.25 FWI points and agree on the class every day. `CFFDRS_PARAMS` takes the program's constants and matches cffdrs to 0.006. Keep one printing for the whole life of a stored chain. - **No overwintering, no snow.** The chain does not stop or restart with the season; that is the caller's choice. Reference: Van Wagner, C.E. (1987), Development and structure of the Canadian Forest Fire Weather Index System, Forestry Technical Report 35.