Metadata-Version: 2.4
Name: geocrc
Version: 0.1.0
Summary: GeoCRC: conformal risk control calibrated within geographic regions, with time-forward evaluation
Author: Xiayin Lou, Ying Jin
Author-email: Peng Luo <peng-luo@uiowa.edu>
License-Expression: MIT
Project-URL: Homepage, https://peng-luo.com/geocrc/
Project-URL: Source, https://github.com/Vezarachan/GeoCRC
Project-URL: Paper, https://peng-luo.com/geocrc/GeoCRC_preprint.pdf
Keywords: conformal risk control,conformal prediction,GeoAI,uncertainty,disaster management,spatial
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy
Requires-Dist: pandas
Requires-Dist: scipy
Requires-Dist: scikit-learn
Provides-Extra: regions
Requires-Dist: libpysal; extra == "regions"
Requires-Dist: joblib; extra == "regions"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Dynamic: license-file

# GeoCRC — geospatial conformal risk control for decisions taken from GeoAI models

Code for *"GeoCRC: Regionally Risk-controlled Spatial Decision Making for Disaster Management"*
by Xiayin Lou, Ying Jin and Peng Luo (preprint, 2026).
[Paper (PDF)](https://peng-luo.com/geocrc/GeoCRC_preprint.pdf) ·
[Project page](https://peng-luo.com/geocrc/) ·
[Online supplement](https://peng-luo.com/geocrc/supplement.html) ·
[PyPI](https://pypi.org/project/geocrc/)

> Naming note: the method is implemented in the `geocrc` package (`src/geocrc/`). In the output
> tables of the analysis, `RegimeCRC (...)` is GeoCRC (its working name during the analysis) and
> `Global CRC` is the paper's standard CRC.

GeoCRC is a post-hoc, model-agnostic layer between a GeoAI model and a decision. The decision maker
states what counts as a failure (the loss) and how often it may occur on average (the tolerance
α). GeoCRC then chooses, within each expert-defined region and from that region's earlier events
only, the least cautious setting of the decision rule whose expected loss stays within α
(conformal risk control applied within regions). It reports the cost of each regional promise and
defers the decision to experts where a region has too few earlier events
(fewer than ⌈1/α − 1⌉). The paper applies it to flood alerts (LSTM forecast, 17 HydroBASINS
regions), wildfire flags (XGBoost classifier, 9 GACCs) and post-earthquake intensity (an intensity
prediction equation used outside California, 2 NSHM regions) in North America.

## Install

```bash
pip install geocrc                    # the method only, with numpy, pandas, scipy and scikit-learn
```

To reproduce the paper, clone this repository and, in its folder:

```bash
pip install -e .                      # the geocrc package from this folder
pip install -r requirements.txt       # the libraries of the three cases
```

## In ten lines

```python
import numpy as np, geocrc

floods = geocrc.load_flood_example()                 # region, water_year, r (forecast / flood level before each flood)
mults = np.r_[np.geomspace(5, 0.1, 100), 0.0]        # candidate alert multipliers, least to most cautious
units = list(floods[floods.water_year < 2013].groupby(["region", "water_year"]).r)   # past region-years
losses = np.array([[np.mean(r < m) for m in mults] for _, r in units])            # share of floods missed at each m
regions = [g for (g, _), _ in units]

model = geocrc.GeoCRC(alpha=0.3, grid=mults).fit(losses, regions)
model.summary()        # one multiplier per region for 2013, e.g. Rio Grande 0.20, Mackenzie 0.81; NaN = defer to experts
```

`GeoCRC(alpha, grid).fit(losses, regions=None)` with no regions is standard CRC, one calibration for the whole territory.
`geocrc.replay(time, losses, alpha, regions, grid, start=2007)` makes the decision for every unit from strictly earlier
units of its region and returns the realised losses, for checking the promise after the fact. The steps below do the
same with the lower-level functions.

## Quickstart: flood alerts

`python examples/flood_quickstart.py` runs every step below on the paper's flood data
(`examples/flood_floods.csv`, 19,247 floods in 17 regions, water years 1998–2018).

**The decision.** A forecast model gives every basin, each evening, the highest flow expected in the
next three days. The rule alerts a basin when this forecast reaches m times the basin's flood level.
The setting m is what GeoCRC chooses: a lower m means more alerts, fewer missed floods and more days
on alert. **The risk** to control is the share of a region's floods that are missed, and the
tolerance is α = 0.3: on average, at most 30% of a region's floods may be missed. **The data** is
one row per past flood, with its region, its water year and r, the forecast on the evenings before
the flood divided by the flood level. A flood is warned at m exactly when r ≥ m.

### Step 1. Define the loss of a unit at every setting

A unit is what one decision covers, here a region-year. Its loss curve gives its loss at every
candidate setting, ordered from the least to the most cautious.

```python
import numpy as np, pandas as pd
from geocrc import crc_threshold, time_forward, has_loss, above_alpha_test

floods = pd.read_csv("examples/flood_floods.csv")   # region, water_year, r
# Candidate multipliers m, from the least to the most cautious: 100 values from 5 down to 0.1, evenly spaced on a
# log scale (each about 4% below the previous), then 0, which alerts every day and so misses no flood.
# GeoCRC picks the first, least cautious one whose calibration risk stays within alpha.
mults = np.r_[np.geomspace(5, 0.1, 100), 0.0]
grid = np.arange(len(mults))                         # GeoCRC works on positions in this list: larger = more cautious
ALPHA = 0.3

def loss_curve(r):
    """Share of a region-year's floods that each multiplier misses."""
    r = np.asarray(r)
    return np.array([np.mean(r < m) for m in mults])
```

### Step 2. Decide: one setting per region, from its own history

```python
past = floods[floods.water_year < 2013]              # deciding for water year 2013: only earlier years
setting = {}
for region, d in past.groupby("region"):
    curves = np.array([loss_curve(y.r) for _, y in d.groupby("water_year")])
    k = crc_threshold(curves, grid, ALPHA)           # NaN: too little history, defer to experts
    setting[region] = mults[int(k)]
print(round(setting["Rio Grande"], 2), round(setting["Mackenzie"], 2))   # 0.2 0.81
```

The decision for every evening of 2013 is then: **alert basin b of region g when its forecast reaches
`setting[g]` times its flood level.** The model misses many floods in the Rio Grande, so this region
alerts already at 0.20 of the flood level; in the Mackenzie it alerts at 0.81. Pooling all regions,
standard CRC would use one multiplier, 0.59, everywhere. A region with fewer than ⌈1/α − 1⌉ = 3
earlier years with floods gets NaN: GeoCRC defers its decision to experts. Next year, 2013 joins the
history and the settings are recomputed.

### Step 3. Check the decisions after the fact

`time_forward` replays Step 2 for every region and year, each time from the years before it, and
returns the setting and the realised loss of each unit.

```python
ry = [(g, y, loss_curve(d.r)) for (g, y), d in floods.groupby(["region", "water_year"])]
region = np.array([g for g, _, _ in ry]); year = np.array([y for _, y, _ in ry]); curves = np.array([c for *_, c in ry])
score = year >= 2007                                 # decide 2007-2018
k_geo, loss_geo = time_forward(year, region, curves, grid, ALPHA, calib=has_loss(curves), score=score)
res = pd.DataFrame({"region": region, "year": year, "geocrc": loss_geo})[score]
print(res.groupby("region").geocrc.mean().round(3))  # each region's share of floods missed, e.g. Rio Grande 0.174
```

The example script adds standard CRC and the regional test. Standard CRC leaves the Rio Grande at
0.685, Texas Gulf at 0.546 and the US Northeast at 0.435, all significantly above α. GeoCRC brings them
to 0.174, 0.226 and 0.212, and no region is significantly above α (Table O2.1 of the online supplement).

### Your own loss and risk

The loss can be anything you can compute for a past unit at every setting, if it

- is bounded, between 0 and some B (pass `B=` when B is not 1);
- does not grow as the setting becomes more cautious;
- is at most α at the most cautious setting (alerting every day misses no flood).

The risk is the expected loss of a new unit, and α is its tolerance. For example, to allow on average
at most one missed flood per region and year, count the missed floods (capped at 5):

```python
def missed_floods(r, cap=5):
    r = np.asarray(r)
    return np.array([min((r < m).sum(), cap) for m in mults])

curves = np.array([missed_floods(y.r) for _, y in past[past.region == "Rio Grande"].groupby("water_year")])
k = crc_threshold(curves, grid, alpha=1.0, B=5)      # Rio Grande, 2013: multiplier 0.12
```

Other decisions follow the same pattern. For an intensity warning (the paper's earthquake case), the
setting is a margin λ added to the predicted intensity, and the loss is the share of places whose
observed intensity exceeds the issued one. For such losses, `step_curve(r, grid)` builds the curve
from r = observed − predicted, the margin each place would have needed.

Main functions:

| Function | What it does |
|---|---|
| `crc_threshold`, `plugin_threshold` | the CRC setting from past loss curves (with the floor), and the plug-in baseline |
| `time_forward` | GeoCRC: one setting per region and time from strictly earlier units of the region |
| `time_forward_nested` | the same with learned sub-regions inside a parent partition (GeoRegime ablation) |
| `audit.summarise`, `summarise_weighted` | regional losses with unit or year-clustered bootstrap intervals |
| `above_alpha_test`, `paired_test`, `between_region_test` | regions above α (Holm), paired rule comparisons, between-region spread (permutation) |
| `effective_target`, `min_units`, `unit_status` | effective target α_n, minimum history, certified / non-informative / deferred |
| `regimes.nested_georegimes` | GeoRegime: data-driven regions where no expert partition exists |

## Layout

```
src/geocrc/                       the method: CRC within regions, time-forward calibration, regional tests, learned regions; unit tests
src/paperfigs/                    figure style and plotting helpers of the paper (not part of the method)
examples/                         the quickstart on the paper's flood data (flood_quickstart.py, flood_floods.csv)
docs/                             the web site, served by GitHub Pages: project page (index.html) and online supplement (supplement.html)
experiments/
  EXP-003-flood-lstm/             flood alerts: data, LSTM training, GeoCRC runs, sensitivity, figures
    figure_redesign_2026-10-13/final/   flood figures (method, results, supplement)
  EXP-004-fpa-fod/                wildfire flags: data, feature table, XGBoost, GeoCRC runs, figures
    figure_redesign/              wildfire figures
  EXP-001-earthquake-ipe/         earthquake intensity: DYFI data, IPE, GeoCRC runs, figures
    figure_redesign/              earthquake figures
  EXP-005-risk-budget/            cross-case analyses, supplementary tables, Figures 1-3
```

Every script writes its outputs (CSV tables) next to itself; figures of the case folders go to their
`out/` folder, the cross-case figures to `figures/` and the LaTeX tables to `manuscript/tables/`.

## Environment

Python 3.11. Tested with the versions in `requirements.txt`:

```
pip install -r requirements.txt
```

Point the code to a local data folder (raw data and large intermediate files live there) and make
the package importable:

```bash
export REGIMECRC_DATA=/path/to/data          # see "Data" below for its layout
export PYTHONPATH=$PWD/src
mkdir -p figures manuscript/tables data/processed
```

## Data

All data are public. The fetch scripts download them into `$REGIMECRC_DATA`; the links below are the
sources and versions used.

| Case | Data | Version | Link | Place under `$REGIMECRC_DATA/` |
|---|---|---|---|---|
| Flood | Caravan (CAMELS and HYSETS subsets: ERA5-Land forcing, streamflow, attributes), CC BY 4.0 | v1.6 | https://doi.org/10.5281/zenodo.15529786 (`Caravan-nc.tar.gz`, 24.8 GB) | `caravan/` (`fetch.py --only caravan`) |
| Flood | HydroBASINS, North America (`na`) and Arctic (`ar`), levels 2, 3 and 4 | v1c | https://www.hydrosheds.org/products/hydrobasins (e.g. https://data.hydrosheds.org/file/hydrobasins/standard/hybas_na_lev03_v1c.zip) | `caravan/hydrobasins/` (`fetch.py --only hybas` gets level 3) |
| Wildfire | Fire Program Analysis fire-occurrence database (FPA FOD), 1992-2024 | 7th edition (RDS-2013-0009.7) | https://doi.org/10.2737/RDS-2013-0009.7 | `fpa_fod/fpa_fod_7th/` |
| Wildfire | gridMET daily fire weather (erc, bi, fm1000, vpd, vs, th) | 1991-2024 | https://www.climatologylab.org/gridmet.html (files: https://www.northwestknowledge.net/metdata/data/) | `fpa_fod/gridmet/` |
| Wildfire | NIFC Geographic Area Coordination Center boundaries | current public layer | https://data-nifc.opendata.arcgis.com/ (GACC Boundaries) | `fpa_fod/gacc/nifc_gacc_boundaries.geojson` |
| Earthquake | USGS ComCat catalogue and "Did You Feel It?" 1 km boxes, M ≥ 4.5, 2000-2024 | queried 2026-10 | https://earthquake.usgs.gov/fdsnws/event/1/ | `eq_dyfi/` (`fetch.py list / fetch / build`) |
| Earthquake | USGS NSHM 1996-2018 WUS/CEUS boundary | nshmp-haz 2.11.4 | https://code.usgs.gov/ghsc/nshmp/nshmp-haz/-/raw/2.11.4/etc/nshm/wus-ceus-boundary.geojson | `eq_dyfi/aux/nshm2014-2018_wus-ceus-boundary.geojson` |
| Earthquake | USGS NSHM 2023 active-crust grid polygon (boundary sensitivity) | nshm-conus 6.0.0 | https://code.usgs.gov/ghsc/nshmp/nshms/nshm-conus/-/raw/6.0.0/active-crust/grid/features/grid-system-active.geojson | `eq_dyfi/aux/nshm2023_grid-system-active.geojson` |
| Earthquake | GHS-POP population grid, epoch 2020, 1 km Mollweide (people issued MMI ≥ VI) | R2023A | https://jeodpp.jrc.ec.europa.eu/ftp/jrc-opendata/GHSL/GHS_POP_GLOBE_R2023A/GHS_POP_E2020_GLOBE_R2023A_54009_1000/V1-0/GHS_POP_E2020_GLOBE_R2023A_54009_1000_V1_0.zip | `eq_dyfi/aux/ghs_pop/` |

The fetch and build steps (run from each case folder):

```bash
# flood
python experiments/EXP-003-flood-lstm/fetch.py --only hybas,caravan
# wildfire
python experiments/EXP-004-fpa-fod/fetch.py --out $REGIMECRC_DATA/fpa_fod
python experiments/EXP-004-fpa-fod/build.py                       # -> fpa_fod/fod_features.parquet
# earthquake
cd experiments/EXP-001-earthquake-ipe
python fetch.py list --minmag 4.5 && python fetch.py fetch --minmag 4.5
python fetch.py add --event nc75095651 --minmag 4.5               # 2024 Cape Mendocino mainshock, outside the query box
python fetch.py build --minmag 4.5                                # -> data/processed/eq_dyfi_boxes_conus_m4.5.parquet
```

## What runs where

- **Stage 1 — models** (the only long step): the flood LSTM is trained once on water years
  1982-1997 and frozen (`EXP-003/train.py`, writes `lstm.pt` and the forecasts `pred.parquet`;
  `train.py --basins basins.csv --train-end 1993-09-30 --tag _s93` trains the structure-fold model
  used only by the GeoRegime ablation). The wildfire XGBoost model is refit inside
  `EXP-004/run.py` (fixed settings, `random_state=0`). The earthquake model is a fixed equation.
- **Stage 2 — calibration and audit** (CPU, minutes per run): the case runners score every
  region-year or event time-forward under no calibration, standard CRC, the regional plug-in and
  GeoCRC, and write the unit tables and summaries.
- **Stage 3 — figures and tables**: read only the CSV outputs of Stage 2.

Order per case:

```bash
# flood (EXP-003)
python train.py && python train.py --basins basins.csv --train-end 1993-09-30 --tag _s93
python run.py && python sweep.py && python realism.py
python fig_extracts.py && python fig_extract_floods.py && python figures.py table
# wildfire (EXP-004)
python run.py && python sweep.py && python realism.py && python x10_recalibration.py
python figure_redesign/fire_extract.py
# earthquake (EXP-001)
python run.py && python sweep.py && python realism.py && python x2_calib2007.py
python figure_redesign/eq_extract.py
```

## Reproducing the paper

After Stage 2 of all three cases (commands run from the folder of the script):

| Paper element (output file in `figures/` or `manuscript/tables/`) | Command |
|---|---|
| Fig. 1 (`fig_concept`) | drafted from components by `EXP-005/fig_component_*.py` and `fig_concept.py`; assembled in a vector editor (source `figures/src/fig_concept.afdesign`) |
| Fig. 2 (`fig_method`, simulated) | `python EXP-005/fig_method.py` (writes `out/method_draft`; finished in a vector editor, source `figures/src/fig_method.afdesign`) |
| Fig. 3 (`fig_design`) | `python EXP-005/fig_design.py` |
| Fig. 4, 7 (`fig_flood-method`, `fig_flood-results`); static tolerance figure `figS_flood-tolerance` | `python EXP-003/figure_redesign_2026-10-13/final/fig_flood_{method,results,supp}.py` (writes `out/`) |
| Fig. 5, 8 (`fig_wildfire-method`, `fig_wildfire-results`); static tolerance figure `figS_wildfire-tolerance` | `python EXP-004/figure_redesign/fig_fire_{method,results,supp}.py` (writes `out/`) |
| Fig. 6, 9 (`fig_earthquake-method`, `fig_earthquake-results`); static tolerance figure `figS_earthquake-tolerance` | `python EXP-001/figure_redesign/fig_eq_{method,results,supp}.py` (writes `out/`) |
| Supplementary Fig. S1 (`figS_regions`) | `python EXP-005/fig_regions.py` |
| Web site (`docs/`, served by GitHub Pages; a copy in `manuscript/online/`): the project page `index.html` (animations of the research problem and of the method, summary, maps of the regional results) and the online supplement `supplement.html` (Sections O1-O9) | `python EXP-005/build_online_supplement.py` (reads the outputs listed below and the data root; data of the two animations from `online_method_steps.py`) |
| O2 regional results, O4 tolerance sweep | `python EXP-005/supp_tables.py` |
| O3 power of the regional test; regions above α by chance | `python EXP-005/power_analysis.py`; `python EXP-005/x9_chance_count.py` |
| Fig. 10 (`fig_cost`); O4 cost at equal worst-region risk | `python sweep.py --fine` in `EXP-001`, `EXP-003` and `EXP-004` (tolerance grid of step 0.005), `python EXP-005/figures.py` (risk-budget table and frontier), then `python EXP-005/fig_cost.py` and `python EXP-005/supp_tables_r6.py` |
| O5 agency-style rules and recalibration | `python EXP-005/supp_realism_tables.py` (from each case's `realism_table.csv`) |
| O6 robustness | flood: `fl7_static_indices.py --predict` then `run.py --tag _fl7`; `run.py --obs-only`; `run.py --decluster 7`; `run.py --rp 5`; `fl8_q2pred.py`. Wildfire: `fi7_sensitivity.py`, `c8_default_cutoff.py`. Earthquake: `x2_calib2007.py` |
| O7 learned regions | printed by the three `run.py` (GeoRegime rows of the unit tables) |
| O7 scale and zoning | `python EXP-003/x5_maup.py` |
| O7 misses within regions (static figure `figS_basin-misses`) | `python EXP-003/x8_basin_miss.py` |
| O8 short history (static figure `figS_short-history`) | `python EXP-003/x6_short_history.py && python EXP-005/fig_short_history.py` |
| O9 stability over time | `python EXP-005/x11_time_trend.py` |
| Discussion, Spearman ρ of λ against forecast skill | `python EXP-005/confidence_extract.py` |
| Quickstart data (`examples/flood_floods.csv`) | `python EXP-003/example_data.py` (from `fig_extract_floods.csv`) |
| Unit tests | `python -m pytest src/geocrc/tests -q` |

`EXP-00N` stands for `experiments/EXP-00N-...`.

## Determinism

Calibration, audits and tables are deterministic given the model outputs; the bootstrap intervals
and permutation tests use fixed seeds. The LSTM is trained with fixed seeds (`torch.manual_seed(0)`),
but retraining on other hardware may change the forecasts slightly; the XGBoost model uses
`random_state=0`.

## Citing

```bibtex
@misc{lou2026geocrc,
  title  = {GeoCRC: Regionally Risk-controlled Spatial Decision Making for Disaster Management},
  author = {Lou, Xiayin and Jin, Ying and Luo, Peng},
  year   = {2026},
  note   = {Preprint},
  url    = {https://peng-luo.com/geocrc/}
}
```

## License

MIT (see `LICENSE`). The data are not covered by this licence; each source keeps its own terms (for example, Caravan is CC BY 4.0).
